【问题标题】:What is the return type of boost::bind?boost::bind 的返回类型是什么?
【发布时间】:2011-09-18 17:12:19
【问题描述】:

我想将函数的“绑定器”保存到变量中,以便通过利用其运算符重载设施在以下代码中重复使用它。这是实际执行我想要的代码:

#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
#include <iostream>

class X 
{       
    int n; 
public: 
    X(int i):n(i){}
    int GetN(){return n;}  
};

int main()
{
    using namespace std;
    using namespace boost;

    X arr[] = {X(13),X(-13),X(42),X(13),X(-42)};
    vector<X> vec(arr,arr+sizeof(arr)/sizeof(X));

    _bi::bind_t<int, _mfi::mf0<int, X>, _bi::list1<arg<1> > > bindGetN = bind(&X::GetN,_1);

    cout << "With  n =13 : " 
         << count_if(vec.begin(),vec.end(),bindGetN == 13)
         << "\nWith |n|=13 : " 
         << count_if(vec.begin(),vec.end(),bindGetN == 13 || bindGetN == -13)
         << "\nWith |n|=42 : " 
         << count_if(vec.begin(),vec.end(),bindGetN == 42 || bindGetN == -42) 
         << "\n";

    return 0;                                                                    
} 

困扰我的当然是这行:

bi::bind_t<int, _mfi::mf0<int, X>, _bi::list1<arg<1> > > bindGetN = bind(&X::GetN,_1);

我只是通过故意犯类型错误并分析错误消息来获得类型。这当然不是一个好方法。有没有办法获得“bindGetN”的类型?或者,也许有不同的方法来产生类似的功能?

编辑:我忘了提到使用function 的“标准”建议在这种情况下不起作用——因为我想让我的运算符重载。

【问题讨论】:

    标签: c++ types boost-bind


    【解决方案1】:

    简短的回答是:您不需要知道(实现定义)。 它是一个绑定表达式(std::tr1::is_bind_expression&lt;T&gt;::value 为实际类型生成 true)。

    看看

    1. std::tr1::function&lt;&gt;
    2. BOOST_AUTO()
    3. c++0x 'auto'关键字(类型推断)
      • 很接近 decltype() 可以帮助您更进一步

    1.

    std::tr1::function<int> f; // can be assigned from a function pointer, a bind_expression, a function object etc
    
    int realfunc();
    int realfunc2(int a);
    
    f = &realfunc;
    int dummy;
    f = tr1::bind(&realfunc2, dummy);
    

    2.

    BOOST_AUTO() 旨在支持 c++0x auto 的语义,无需编译器 c++0x 支持:

    BOOST_AUTO(f,boost::bind(&T::some_complicated_method, _3, _2, "woah", _2));
    

    3.

    基本相同,但有编译器支持:

    template <class T> struct DoWork { /* ... */ };
    
    auto f = boost::bind(&T::some_complicated_method, _3, _2, "woah", _2));
    
    DoWork<decltype(T)> work_on_it(f); // of course, using a factory would be _fine_
    

    请注意,auto 可能是针对这种情况而发明的:实际类型是“您不想知道”,并且可能因编译器/平台/库而异

    【讨论】:

    • 谢谢。虽然 #1 没有做我想要的,而 #3 不适合我。 #2 完美地做到了这一点。
    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多