Kos*_*tya 25 c++ types boost-bind
我想将函数的"binder"保存到变量中,通过利用其运算符重载工具在下面的代码中重复使用它.这是实际做我想要的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当然,困扰我的是:
bi::bind_t<int, _mfi::mf0<int, X>, _bi::list1<arg<1> > > bindGetN = bind(&X::GetN,_1);
Run Code Online (Sandbox Code Playgroud)
我只是通过故意制作类型错误并分析错误消息来获得该类型.这当然不是一个好方法.有没有办法获取"bindGetN"的类型?或者,可能有不同的方法来产生类似的功能?
编辑:我忘了提到,所以说,"标准"建议使用function在这种情况下不起作用 - 因为我想让我的运算符重载.
seh*_*ehe 17
简短的回答是:您不需要知道(实现已定义).它是一个绑定表达式(std::tr1::is_bind_expression<T>::value对于实际类型,产生true).
看着
std::tr1::function<>decltype()可以帮助您进一步发展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);
Run Code Online (Sandbox Code Playgroud)
BOOST_AUTO()旨在支持c ++ 0x auto的语义而无需编译器c ++ 0x支持:
BOOST_AUTO(f,boost::bind(&T::some_complicated_method, _3, _2, "woah", _2));
Run Code Online (Sandbox Code Playgroud)
基本相同,但有编译器支持:
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_
Run Code Online (Sandbox Code Playgroud)
请注意,auto可能是针对这种情况发明的:实际类型是"你不想知道",并且可能因编译器/平台/库而异
| 归档时间: |
|
| 查看次数: |
8791 次 |
| 最近记录: |