// 忽略警告
#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;
}