boost::result_of/ref

// 忽略警告
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <assert.h>
#include <iostream>
#include <boost/utility/result_of.hpp>// result_of
#include <boost/typeof/typeof.hpp>// typeid
#include <boost/ref.hpp>// reference_wrapper
#include <set>
using namespace boost;
using namespace std;


typedef double(*Func)(double);

// 正确推导返回相应的类型
template<typename F,typename T>
typename boost::result_of<F(T)>::type call_fun(F f, T t)
{
	return f(t);
}


int main()
{
	Func func = sqrt;
	boost::result_of<Func(double)>::type x = func(5.0);
	cout << typeid(x).name() << x << endl;// double类型的x 

	BOOST_AUTO(X, call_fun(func, 3));// 
	cout << typeid(X).name() << X << endl;// double类型的X

	int a = 10;
	boost::reference_wrapper<int> rw(a);	// 包装int 类型的引用
	assert(a == rw);	// rw隐式转换为int进行比较
	a = 100;
	assert(a == rw);	// 正确
	(int)rw = 10;		// (int&)rw = 10;
	assert(a == rw);	// 正确

	// 引用
	boost::reference_wrapper<int> rw1(rw);// a rw1 rw 都是指向同一块内存
	rw.get() = 200;
	assert((rw1.get() == 200 && a == 200));

	string str;
	boost::reference_wrapper<string> rws(str);// 包装字符串 类型的引用
	*rws.get_pointer() = "boost::reference_wrapper";
	cout << rws.get().c_str() << endl;// boost::reference_wrapper 

	// ref 和 cref封装了boost::reference_wrapper
	float data = 1.1;
	BOOST_AUTO(rw2, boost::ref(data));
	cout << rw2.get() << endl;// 1.1

	string str1;
	BOOST_AUTO(rw3, boost::cref(str1));
	cout << typeid(rw3).name() << endl;
	str1 = "111222333";
	cout << rw3.get().c_str() << endl;// 111222333

	// 判断是否包装过
	assert(boost::is_reference_wrapper<BOOST_TYPEOF(rw2)>::value);
	assert(!boost::is_reference_wrapper<BOOST_TYPEOF(data)>::value);
	// 真实类型
	cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(rw2)>::type).name() << endl; // float
	cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(data)>::type).name() <<endl; // float

	// 解包
	set<int> s;
	BOOST_AUTO(rw4, boost::ref(s));
	boost::unwrap_ref(rw4).insert(12);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值