您的位置:首页 > 其它

boost 11 function/bind 函数与回调

2014-01-01 22:00 483 查看

01 result_of 比auto更强大用于返回值的类型推倒 在编译器做处理


#include <iostream>
#include <string>
#include <assert.h>
#include <vector>

#include <boost/utility/result_of.hpp>

using std::cout;
using std::endl;
using std::string;
using std::vector;

template <typename T, typename T1>
typename boost::result_of<T(T1)>::type call_func(T t, T1 t1)
{
return t(t1);
}

int main()
{
typedef double(*Func)(double d);
Func func = sqrt;

auto x = call_func(func, 5.0);
cout << typeid(x).name() <<endl;

return 0;
}


02 ref 提供了对对象的引用操纵来降低在函数传递过程中对象拷贝 构造带来的消耗 提高了效率 但是不支持函数调用功能C++11的ref是支持的

03 bind 强大的函数适配器 C++11 废除了 bind1st/bind2nd

需要说明的就是bind的返回值问题

对于自定义的函数 加了typedef result_type可以不用指定返回值类型

#include <iostream>
#include <string>
#include <assert.h>
#include <vector>
#include <algorithm>

#include <boost/bind.hpp>

using std::cout;
using std::endl;

struct demo
{
void func()
{
cout << "test" << endl;
}
};

struct func
{
int operator()(int a, int b)
{
return a + b;
}
};
struct func1
{
typedef int result_type;
int operator()(int a, int b)
{
return a + b;
}
};

int main()
{
demo dm;

cout << boost::bind<int>(func(), _1, _2)(10, 20) << endl; // 对于自定义的函数 加了typedef result_type可以不用指定返回值类型
cout << boost::bind(func1(), _1, _2)(10, 20) << endl; // result_type 在内部定义了 所以不用指定返回值的类型
//cout << boost::bind(&point2::print, p2) << endl;

return 0;
}


04 function 函数对象的容器 建议配合bind使用

可以使bind得到结果或者是普通的函数指针

#include <iostream>
#include <string>
#include <assert.h>
#include <vector>
#include <algorithm>

#include <boost/bind.hpp>
#include <boost/function.hpp>

using std::cout;
using std::endl;

struct demo
{
int print(int a)
{
return a;
}
int operator()(int a)
{
return a;
}
};

int f(int x)
{
return x;
}

int main()
{
boost::function<int(int)> func;
assert(!func); // 不持有对象

func = f;

if (func)
{
cout << func(23) << endl;               // 一般的函数
}

// 函数对象
boost::function<int(demo&, int)> func2;     // 这个函数的2个参数
func2 = boost::bind(&demo::print, _1, _2);  // 可以bind不同的接口
demo dm;
cout << func2(dm, 10) << endl;

boost::function<int(int)> func3;            // 这个函数的2个参数
func3 = boost::bind(&demo::print, &dm, 34); // 注意这里是& 因为使用的类似于this的指针

cout << func3(34) << endl;

return 0;
}


与bind的使用 使得接口更加灵活

#include <iostream>
#include <string>
#include <assert.h>
#include <vector>
#include <algorithm>

#include <boost/bind.hpp>
#include <boost/function.hpp>

using std::cout;
using std::endl;

class demo
{
public:
typedef boost::function<int(int)> func_t;

demo() : n_(34){}
void print(func_t func)
{
cout << func(n_) << endl;
}
private:
int n_;
};

class test
{
public:
int llk(int x)
{
return x + 5;
}
};

int main()
{
demo dm;
test ts;

dm.print( boost::bind(&test::llk, &ts, _1) ); // 39 这里绑定了test 的llk函数 可以绑定其它符合function接口的函数

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: