#include <iostream>
#include <vector>
#include <string>
#include <ostream>
#include <algorithm>
#include <boost/function.hpp>
using namespace std;
class some_class
{
public:
void do_stuff(int i) const
{
cout << "some_class i: " << i << endl;
}
};
class other_class
{
public:
void operator()(int i) const
{
cout << "other_class i: " << i << endl;
}
};
int main() {
// CASE ONE
boost::function<void (some_class, int) > f;
// initilize f with a member function of some_class
f = &some_class::do_stuff;
// pass an instance of some_class in order to access class member
f(some_class(), 5);
// CASE TWO
boost::function<void (int) > f2;
// initialize f2 with a function object of other_class
f2 = other_class();
// Note: directly call the operator member function without
// providing an instance of other_class
f2(10);
}
// output
~/Documents/C++/boost $ ./p327
some_class i: 5
other_class i: 10
Run Code Online (Sandbox Code Playgroud)
问题 >当我们通过boost :: function调用一个函数对象时,为什么我们不必为该类提供一个实例来调用这个类成员函数?
是因为我们通过以下方式提供了这样的信息吗?
f2 = other_class();
Run Code Online (Sandbox Code Playgroud)
小智 7
您必须为该类提供一个实例,并且您正在提供一个实例.
boost::function<void (int) > f2;
f2 = other_class();
Run Code Online (Sandbox Code Playgroud)
这构造了一个other_class对象,并将该对象分配给f2.boost::function然后复制该对象,以便在您尝试调用它时,您不需要再次实例化它.