我有一个静态函数Bar::Function(std::string s1, std::string s2, std::string s3 )
,我想将其作为功能指针传递给具有Foo
成员的类boost::function
的构造函数。
但是,这三个字符串是在Foo()
类中创建的,并且在将函数作为功能指针传递给Foo的构造函数时尚不清楚。
我是否应该在main()
中传递三个空字符串?
class Foo(boost::function<int(std::string, std::string, std::string)> fFunction)
{
public:
Foo()
{
fnCallback = fFunction;
}
int Call()
{
return fnCallback("first", "second", "third")
}
protected:
boost::function<int(std::string, std::string, std::string)> fnCallback;
};
int main(int /*nArgc*/, char */*paszArgv*/[])
{
boost::function<int(std::string, std::string, std::string)> fn = boost::bind(Bar::Function, "", "", "");
Foo oFoo(fn);
oFoo.Call();
return 0;
}
class Bar
{
public:
static int Function(std::string s1, std::string s2, std::string s3)
{
std::cout << s1 << s2 << s3 << std::endl;
}
};
编辑:这就是代码的外观。函数指针仅保留函数的地址。调用时会传递参数!
fn = &Bar::Function;
最佳答案
这是一个最小的示例:
#include <iostream>
#include <string>
struct Foo
{
typedef int (*callback_type)(std::string, std::string, std::string);
Foo(callback_type callback)
: _callback(callback)
{}
int operator()()
{
return _callback("1", "2", "3");
}
private:
callback_type _callback;
};
struct Bar
{
static int Function(std::string s1, std::string s2, std::string s3)
{
std::cout << s1 << s2 << s3 << std::endl;
return 0;
}
};
int main()
{
Foo foo(Bar::Function);
foo();
return 0;
}
打印
123\n
。