在C++ 11之前有类似于std :: function的东西吗?

and*_*llr 7 c++ c++11 std-function

std::function<>当C++ 11不可用时,应该使用什么构造作为代理?
替代应该基本上允许从另一个类访问一个类的私有成员函数,如下例所示(不使用std :: function的其他功能).类Foo是固定的,不能改变太多,我只能访问类Bar.

class Foo {
  friend class Bar; // added by me, rest of the class is fixed
  private:

  void doStuffFooA(int i);
  void doStuffFooB(int i);
};

class Bar {
  public:

  Bar( Foo foo, std::function< void (const Foo&, int) > func ) {
    myFoo = foo;
    myFooFunc = func;
  };

  private:

  doStuffBar( const &Foo foo ) {
    myFooFunc( foo, 3 );
  }

  Foo myFoo;
  std::function< void (const Foo&, int) > myFooFunc;
}

int main() {

  Foo foo(...);

  Bar barA( foo, &Foo::doStuffFooA );

  Bar barB( foo, &Foo::doStuffFooB );
  ...
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 10

在C++ 11之前有类似于std :: function的东西吗?

是的.有Boost.Function(boost::function<>),它最近成为C++标准库的一部分,并提供了一个参考实现std::function<>; 同样,Boost.Bind(boost::bind<>())被标准采用并成为std::bind<>().

它实现了一种称为类型擦除的技术,用于保存任何类型的可调用对象.这是一个可能的说明性实现,如何从头开始定义这样的类模板(不要在生产代码中使用,这只是一个例子):

#include <memory>

template<typename T>
struct fxn { };

template<typename R, typename... Args>
struct fxn<R(Args...)>
{

public:

    template<typename F>
    fxn(F&& f) 
        : 
        _holder(new holder<typename std::decay<F>::type>(std::forward<F>(f)))
    { }

    R operator () (Args&&... args)
    { _holder->call(std::forward<Args>(args)...); }

private:

    struct holder_base
    { virtual R call(Args&&... args) = 0; };

    template<typename F>
    struct holder : holder_base
    {
        holder(F&& f) : _f(std::forward<F>(f)) { }
        R call(Args&&... args) { return _f(std::forward<Args>(args)...); }
        F _f;
    };

    std::unique_ptr<holder_base> _holder;
};

#include <iostream>

int main()
{
    fxn<void()> f = [] { std::cout << "hello"; };
    f();
}
Run Code Online (Sandbox Code Playgroud)

  • Iirc`function`也可以在tr1中使用,它在c ++ 11之前很久就在大多数标准库中实现,并且几乎与`boost :: function`相同. (3认同)