C++ boost::bind的返回类型是什么?
我想将函数的“绑定器”保存到一个变量中,通过利用其运算符重载功能在下面的代码中重复使用它。下面是我想要的代码:C++ boost::bind的返回类型是什么?,c++,types,boost-bind,C++,Types,Boost Bind,我想将函数的“绑定器”保存到一个变量中,通过利用其运算符重载功能在下面的代码中重复使用它。下面是我想要的代码: #include <boost/bind.hpp> #include <vector> #include <algorithm> #include <iostream> class X { int n; public: X(int i):n(i){} int GetN(){return n;}
#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;
}
#包括
#包括
#包括
#包括
X类
{
int n;
公众:
X(inti):n(i){}
int GetN(){return n;}
};
int main()
{
使用名称空间std;
使用名称空间boost;
X arr[]={X(13),X(-13),X(42),X(13),X(-42)};
向量向量向量(arr,arr+sizeof(arr)/sizeof(X));
_bi::bind\u t bindGetN=bind(&X::GetN,_1);
cout简单的回答是:您不需要知道(实现定义的)。
它是一个绑定表达式(std::tr1::is\u bind\u expression::value
为实际类型生成true)
看
std::tr1::function
关键词(类型推断)
- 非常接近
decltype()
可以帮助您更进一步
1.
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_
template struct DoWork{/*…*/};
自动f=boost::bind(&T::一些复杂的方法,_3,_2,“woah”,_2));
DoWork work on it(f);//当然,使用工厂也可以_
请注意,auto可能是为这种情况而发明的:实际的类型是“你不想知道”,并且可能因编译器/平台/库而异谢谢。虽然#1不做我想做的事,而#3不适合我。但#2做得很好。
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);
BOOST_AUTO(f,boost::bind(&T::some_complicated_method, _3, _2, "woah", _2));
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_