25

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

#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在这种情况下使用的“标准”建议不起作用——因为我想让我的运算符重载。

4

1 回答 1

17

简短的回答是:您不需要知道(实现定义)。它是一个绑定表达式(std::tr1::is_bind_expression<T>::value对实际类型产生 true)。

看着

  1. std::tr1::function<>
  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 支持的情况下支持 c++0x auto 的语义:

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 :实际类型是“您不想知道”,并且可能因编译器/平台/库而异

于 2011-06-20T13:47:34.500 回答