boost any类库的使用
功能
可以将任何类型值保存到boost::any类中。也可以通过boost::any_cast模板方法来将boost::any类中设置的数据,安全地拿出来。
基本小例子
将任何数据保存到any类中
#include <assert.h>
#include <boost/any.hpp>
#include <string>
#include <vector>
#include <map>
using namespace std;
using namespace boost;
class Student
{
public:
Student() : age_(25) {}
Student(int age) : age_(age) {}
int GetAge() const
{
return age_;
}
private:
int age_;
};
int calc_max(int data1, int data2)
{
return data1 > data2 ? data1 : data2;
}
int main(int argc, char **argv)
{
int a[] = {
1, 2, 3, 4, 5};
vector<int> iv(a, a + 5);
map<string, int> info;
int i = 100;
info["zs"] = 10;
info["ls"] = 5;
//======================支持将任何类型通过构造函数来创建any对象======================
// 将基本数据类型保存到any类中
any any1(10);
any any2("hello world");
any any3(2.5f);
any any4(3.14);
any any5(a);
any any6(&i);
// 将对象保存到any类中
any any7(string("hello world"));
any any8(iv);
any any9(info);
// 将用户自己定义的类型对象保存到any类中
Student stu;
any any10(stu);
// 可以使用某个现有的any对象来进行拷贝构造
any any11(any9);
// ================也可以讲任何类型复制给any对象========
any10 = Student();
any10 = any3;
any10 = 1;
any10 = &calc_max;
any10 = any3;
any10 = vector<int>();
//any any12(int()); //千万不能这样写
//any any12(&calc_max);
//any12 = any10;
return 0;
}
怎么样,很吃惊吧,从上面的代码中,我们可以看到,我们可以将基本数值类型(int、double、float、char、各种指针)、标准库中鲜有的模板类对象、用户自己定义的各种类型。
而且any也支持对于自身的拷贝构造和赋值操作。你会发现,通过这种支持。你可以讲保存int数值的any对象赋值给保存字符串的any对象,那么保存字符串的any对象就会变成保存int数值的any对象。你会发现使用any来接收数据的话,就像使用了某种动态语言。对于c++这种静态语言来讲,真的是实在是太太惊艳了。
而且也支持将任何类型的数值或者对象赋值给现有的any对象。也就是说,你不但可以通过构造器来构造保存任意值的any对象,你还可以将已经保存了某种类型值的any对象中值改变成其他类型。真的是太像动态语言了。
下面说一个有趣的问题,也是使用值来构造any的一个注意点
any stu(Student()); //这儿是我想使用一个默认的Student对象来赋值给stu
注意这样写是不行的,为什么呢?因为这样写等价于any stu(Student(*)())。编译器会把它当做一个函数声明。
对于上面的,我们可以通过这样写any stu(Student(25));
或者: Student tmp; any stu(tmp);
从any对象中获取值
/*
* app.cpp
*
* Created on: 2015年11月3日
* Author: TwoFlyLiu
*/
#include <assert.h>
#include <boost/any.hpp>
#include <boost/type_index.hpp>
#include <string>
#include <vector>
#include <map>
#include <iostream>
using namespace std;
using namespace boost;
template <typename T>
struct append_const_to_ptr
{
typedef const T * type;
};
template <typename T>
struct append_const_to_ptr<const T>
{
typedef const T *type;
};
// 这个宏的设计意图是为了解决,boost any库以数组构造any对象,所产生的类型衰减问题。
// 经过测试:mingw编译器对于int a[]还是const int a[],最后衰减成的类型都是int const*类型。
// 而对于vc编译器来讲,则比较正常,对于int a[],会衰减成int *,对于const int a[],则会衰减成int const *
// 这个宏的目的,就是设置真正的衰减后的类型,这样在any_cast中,就不会发生类型转换的错误
#if defined(__GNUC__)
#define DECAY_ARRAY_TYPE(value_type) append_const_to_ptr<value_type>::type
#elif defined(_MSC_VER)
#define DECAY_ARRAY_TYPE(value_type) value_type *
#endif
int main(int argc, char **argv)
{
int a[5] = {
1, 2, 3, 4, 5};
vector<int> iv(a, a + 5);
map<string, int> info;
int i = 100;
info["zs"] = 10;
info["ls"] = 5;
any object_or_val(i);
// 通过boost::any_cast来从any中获取任何类型的值。
// 有两大种any_cast重载函数,
// 一种是:
// template <typename ValueType> ValueType &any_cast(any &),可能会抛出bad_any_cast异常&#x