我有点搞不懂为什么这个绑定调用不起作用。我已经将问题缩小到试图在对bind的新调用中嵌套bind对象。
#include <iostream>
#include <algorithm>
#include <tr1/functional>
using namespace std;
using tr1::bind;
using namespace std::tr1::placeholders;
double times_2(double a) {
return 2*a;
}
void print_num(double a) {
cout << a << endl;
}
template <typename Oper>
void oper_on_list(Oper op) {
int list[] = {0,1,2,3,4};
for_each(list, list+5, bind(print_num, bind(op, _1))); // This works!
for_each(list, list+5, bind(print_num, bind(op, bind(op, _1)))); // This doesn't!
}
int main() {
oper_on_list(bind(times_2, _1));
return 0;
}在这里,我从我的编译器得到一条no matching function for call to 'bind'消息。( G++ 4.2.1或Apple LLVM3.0)。
(实际上是no matching function for call to object of type 'std::tr1::_Bind<double (*(std::tr1::_Placeholder<1>))(double)>')
这里的目标是在不同的绑定中重用绑定对象。根据我所能总结出来的,问题是使用第二个bind调用的结果作为已经创建的bind调用的参数。有什么办法可以绕过这个问题吗?
我认为这也可能有助于阐明这种情况?:
template <typename T>
void print(T t) {
cout << t << endl;
}
template <typename Oper>
void oper_on_list(Oper op) {
int list[] = {0,1,2,3,4};
for_each(list, list+5, bind(print, bind(op, _1))); // This doesn't work
for_each(list, list+5, bind(print<double>, bind(op, _1))); // This does
for_each(list, list+5, bind<void(*)(double)>(print, bind(op, _1))); // So does this!
}这里的问题是,我认为,它很难推导出基于bind(op, _1)的打印模板规范。虽然我不确定为什么它不能..。
但无论哪种方式,指定它似乎都能解决问题。不幸的是,我不知道如何在原始示例中指定模板,因为我不知道Oper是什么!
任何帮助都将不胜感激!:D谢谢!
============================
更新!现在的问题是:为什么在没有C++11的情况下不能编译?据我所知,它没有任何C++11特有的特性。有没有办法在没有C++11的情况下完成同样的任务?也许是一种不同的代码设置方式?
============================
更新2!嗯,这在boost::bind中有效,所以我猜这只是tr1::bind的一个问题。
发布于 2013-02-10 14:48:32
不管怎样,这对于boost::bind是有效的。
显然,这只是tr1::bind pre-C++11中的一个bug。
https://stackoverflow.com/questions/14471541
复制相似问题