c++ - 使用 boost::function 和 boost::bind 确定仿函数中的对象和方法

标签 c++ boost-bind

我想获取指向对象的指针以及仿函数将从使用 boost::function 和 boost::bind 构造的仿函数调用哪个方法的指示。 这将使我能够自动确定必须执行哪一组仿函数的顺序。

以下(伪)代码(请参阅POINTER_OFMETHOD_OF)显示了我正在尝试执行的操作:

class myClassA
{
  public:
    DoIt(int i) { return i+i; }
};

class myClassB
{
  public:
    DoItToo(double d) { return d*d; }
};

typedef boost::function0<int> Functor;

myClassA classA;
myClassB classB;

Functor funcA = boost::bind( &myClassA::DoIt, &classA, 10 );
Functor funcB = boost::bind( &myClassB::DoItToo, &classB, 12.34 );

// Create a vector containing some functors and try to determine the objects
// they are called upon and the methods they invoke
std::vector<Functor> vec;
vec.push_back( funcA );
vec.push_back( funcB );

for (int i = 0; i < vec.size();i++)
{
  if (POINTER_OF(vec[i]) == &classA)
  {
    // This functor acts on classA
    if (METHOD_OF(vec[i]) == &myClassA::DoIt)
    {
      // This functor calls the 'DoIt' method.
    }
    else if (METHOD_OF(vec[i]) == &myClassB::DoItToo)
    {
      // This functor calls the 'DoItToo' method.
    }
  }
  // etc...
}

提前致谢!

最佳答案

我知道以下内容并不是对您问题的严格回答。

不要这样做。 请改用多态性。这是我在当前项目代码中看到的最奇怪的事情之一:如果函数指针指向“someFunction” - 执行一些额外的操作。

使用装饰器设计模式,您可以添加额外的行为,而无需对类进行太多更改。这将使用 Decorator::DoIt 扩展您的 myClassA::DoIt。

http://en.wikipedia.org/wiki/Decorator_pattern

关于c++ - 使用 boost::function 和 boost::bind 确定仿函数中的对象和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/673731/

相关文章:

c++ - 如何在指定时间自动打开计算机

c++ - 在 std::string::find 上使用 boost::bind 编译失败

c++通用指针(成员?)函数

c++ - 创建一个字符串变量并要求在同一行输入?

c++ - Protocol Buffers - 读取所有消息通用的 header (嵌套消息)

c++ - 在 lambda 函数 g++-4.8 中调用继承的 protected 子类型

c++ - g++ 编译器无法识别 lex 的内置 input() 函数

c++ - 使用 boost::bind 进行部分绑定(bind)

c++ - boost::bind 何时将参数转换为所需的类型?

c++ - 比较 Boost.Bind 返回的对象?