2013-04-09 86 views
0

我使用boost ::功能是这样的:的boost ::绑定的隐式转换提振::函数或函数指针

template<class T1> 
void run(boost::function<void (T1)> func, string arg) 
{ 
    T1 p1 = parse<T1>(arg); 
    func(p1); 
} 

当这样使用,一切正常:

void test1(int i) 
{ 
    cout << "test1 i=" << i << endl; 
} 

... 

boost::function<void (int)> f = &test1; 
run(f, "42"); 

我希望能够将原始函数指针直接传递,所以我超载这样的run()函数:

template<class T1> 
void run(void (*func)(T1), string arg) 
{ 
    T1 p1 = parse<T1>(arg); 
    (*func)(p1); 
} 

... 

run(&test1, "42"); // this is OK now 

现在,我想能够将boost :: bind的结果传递给run()函数。就像这样:

void test2(int i, string s) 
{ 
    cout << "test2 i=" << i << " s=" << s << endl; 
} 

... 

run(boost::bind(&test2, _1, "test"), "42"); // Edit: Added missing parameter 42 

但是这不会编译:编辑

bind.cpp: In function ‘int main()’: 
bind.cpp:33:59: error: no matching function for call to ‘run(boost::_bi::bind_t<void, void (*)(int, std::basic_string<char>), boost::_bi::list2<boost::arg<1>, boost::_bi::value<std::basic_string<char> > > >, std::string)’ 
bind.cpp:33:59: note: candidates are: 
bind.cpp:7:6: note: template<class T1> void run(boost::function<void(T1)>, std::string) 
bind.cpp:14:6: note: template<class T1> void run(void (*)(T1), std::string) 

我应该如何运行超载()接受的boost :: bind()的?

编辑2

我知道我能做到这一点是这样的:

boost::function<void (int)> f = boost::bind(&test2, _1, string("test")); 
run(f, "42"); 

但我想使用是更简洁。

编辑3

更改的run()的原型来自run(boost::function<void (T1)>, T1)run(boost::function<void (T1)>, string)阐述实际使用情况。参考。伊戈尔R.的回答

整个源文件可以得到here

+0

没有“隐式投射”这样的事情。强制转换是您在源代码中编写的内容,以告知编译器进行转换。编译器可以在没有转换的情况下进行转换;这种转换是“隐式转换”。当你使用强制转换时,它是一个“显式转换”。 – 2013-04-09 10:03:10

+0

确实。问题标题应该改变。 – anorm 2013-04-09 11:05:42

回答

1

无论function也没有bind的结果类型可以转化为一个函数指针,所以不能将它们与当前传递给run功能签名。

但是,你可以改变run签名,以允许它接受任何调用

template<class F, class A1> 
void run(F f, A1 arg) 
{ 
    f(arg); 
} 

现在你可以将一个指针传递功能,粘合剂,boost::function或者您希望什么都调用 - 只要因为它期望1个参数。 (但是请注意,使用这个微不足道的签名run将不会forwardf无缝对应的参数。)

+0

是的,解决了我描述的问题(+1)。但是,实际的run()函数需要知道参数的类型,参数不是真实世界函数的一部分。 – anorm 2013-04-09 07:55:08

+0

真实世界函数使用参数类型来调用一个模板化的字符串解析器,以便我可以调用一个函数,给它一个字符串参数,并且run()函数将参数解析为正确的类型并调用函数 – anorm 2013-04-09 07:56:47

+0

我编辑过这个问题以反映这一要求。 – anorm 2013-04-09 08:45:38