在对 tr1::bind() 的新调用中嵌套来自 tr1::bind() 的 tr1::bind<> 对象
Nesting a tr1::bind<> object from tr1::bind() in a new call to tr1::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 LLVM 3.0)。
(实际上,no matching function for call to object of type 'std::tr1::_Bind<double (*(std::tr1::_Placeholder<1>))(double)>'
)
此处的目标是在不同的绑定中重用绑定对象。从我能够归结为的内容来看,问题是使用第二个绑定调用的结果作为已创建的绑定调用的参数。有什么办法可以解决这个问题吗?
我认为这也可能有助于阐明情况?
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 的功能。有没有办法在没有C++11的情况下完成同样的任务?也许是设置代码的不同方法?
====
============================更新2!好吧,这适用于 boost::bind,所以我想这只是 tr1::bind 的问题。
好吧,无论如何,这适用于boost::bind。
所以显然它只是 tr1::bind pre-C++11 中的一个错误。
相关文章:
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- boost::bind()类似的东西,但用于函数调用
- 使用 std::应用于 std::bind
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- std::bind on statd::array 的运算符 []
- std::bind c++ in if statement
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 试图克服 std::bind 编译错误
- c++ std::bind within function
- std::bind to void* to std::function
- std::bind,无法让具有单个参数的方法工作
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 在调用 std::bind 的产品后意外调用析构函数
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 使用 std::tr1::bind 或 std::tr1::mem_fn 时,可以使用 std::not1 的替代方案
- 用std::tr1::bind替换boost::bind出现问题
- 在对 tr1::bind() 的新调用中嵌套来自 tr1::bind() 的 tr1::bind<> 对象
- 在客户端代码的不同部分同时使用boost::bind和std::tr1::bind