c++ - 指向函数指针返回的对象实例的函数指针

标签 c++ boost

我是 C++ 的新手。我想制作一个 std::map,其中的 get-method 名称字符串映射了它们各自的 get-method。这些将被循环并显示通过 get-method 获得的值以及方法名称。我将遍历 A 类型的几个实例。我发现 boost/function 对于在 A 中存储 get 方法非常有用。但是,A 也有一个 B 类型的实例,它有自己的 get 方法。如何访问 B 中的 get 方法?

这是我当前的代码(行 mapping["B_Nine"] = &B::(&A::getB::nine 是错误的,但到目前为止我的最佳猜测)...

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <iostream>
#include <map>
#include <string>
#include <functional>

class B
{
public:
    B();
    ~B();
    int nine() {return 9;}
};

B::B()
{

}

B::~B()
{

}

class A 
{
public:
    A();
    ~A();
   int one () {return 1;}
   int two () {return 2;}
   B getB() {return b;}
   B b;
};

A::A()
{   
   b = B();
}

A::~A()
{

}


typedef std::map<std::string,boost::function<int (A*)>> str_func_map;

int main()
{

    str_func_map mapping;

    mapping["One"] = &A::one;
    mapping["Two"] = &A::two;
     mapping["B_Nine"] = &B::(&A::getB)::nine //This line is wrong - how should 
                                              //it be done correctly??

    A* a = new A();

    for (str_func_map::iterator i = mapping.begin(); i != mapping.end(); i++)
    {
        std::cout<< i->first << std::endl;
        std::cout<< (i->second)(a) << std::endl;
    }

    system("pause");
}

最佳答案

// free function
int callMethodOfB(A *a, std::function<int(B*)> method) {
   return method(&(a->getB()));
}

mapping["B_Nine"] = std::bind<int>(&callMethodOfB, std:placeholder::_1, &B::nine);

mapping["B_Nine"] = [] (A *a) { return a->getB().nine(); }

关于c++ - 指向函数指针返回的对象实例的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25801131/

相关文章:

c++ - 在类 : scoped_ptr or shared_ptr? 中将智能指针作为参数传递

c++ - 如何在 Boost::Spirit::Lex 中使用指针作为标记属性?

c++ - 与转换相关的堆损坏错误

c++ - Visual Studio C++ 和 boost 库 : cannot find function definition only when BOOST_FOREACH is present

C++ 将 Vector<BYTE> 转换为第一个 vector 字节为 0 的字符串

c++ - 如何在没有任何断言的情况下构建 imagemagick

c++ - 尝试将 boost.serialization 包含到我的 VS 项目时遇到问题

c++ - 除非已经转义,否则如何替换所有出现的字符串或字符?

C++ 模板化工厂构造函数/反序列化

c++ - 基于 C++ 标准的定义实现 `is_similar` 类型特征