c++ - 在对 tr1::bind() 的新调用中嵌套来自 tr1::bind() 的 tr1::bind<> 对象

标签 c++ templates boost-bind tr1

我有点困惑为什么这个绑定(bind)调用不起作用。我已将问题缩小到尝试在新的绑定(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'来 self 的编译器的消息。 (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)>')

这里的目标是在不同的绑定(bind)中重用绑定(bind)对象。从我已经能够归结为,问题是使用第二个绑定(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 的功能。有没有办法在没有 C++11 的情况下完成同样的任务?也许是另一种设置代码的方法?

============================

更新 2! 好吧,这适用于 boost::bind,所以我猜这只是 tr1::bind 的问题..

最佳答案

好吧,无论如何这都适用于 boost::bind。

很明显这只是 tr1::bind pre-C++11 中的一个错误..

关于c++ - 在对 tr1::bind() 的新调用中嵌套来自 tr1::bind() 的 tr1::bind<> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14471541/

相关文章:

c++ - 复制初始化 - 从 'int' 到非标量类型的转换

c++ - 使用 boost::bind 将回调发布到任务队列

c++ - 没有用于调用 boost::condition_variable::wait 的匹配函数

c++ - Unresolved bind 和 make_pair 过载

c++ - 何时删除复制构造函数和赋值运算符?

c++ - 在 typedef 结构体上使用 sizeof 运算符

c++ - 如何摆脱 C++ 中的枚举不匹配错误?

c++ - OpenCV DescriptorMatcher radiusMatch 和 knnMatch 结果格式

c++ - C++ 中的 Trie 实现

C++ 生成可变数量的嵌套 FOR 循环