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

时间:2013-01-23 02:36:30

标签: c++ templates boost-bind 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的问题。

1 个答案:

答案 0 :(得分:0)

嗯,无论如何,这适用于boost :: bind。

显然,这只是tr1 :: bind pre-C ++ 11中的一个错误。

相关问题