获得可变参数列表中最大类型大小
可变参数,以递归的形式加以判断是否为最大类型:
template<typename T, typename...TS>
struct variant_helper
{
static const size_t size =
sizeof(T) > variant_helper<TS...>::size ?
sizeof(T): variant_helper<TS...>::size;
}
// 模板特化,有点类似于递归推出的情形
template<typename T>
struct variant_helper<T>
{
static const size_t size =
sizeof(T);
}
variant_helper<char, short, int, long, float, double>::size
template<typename... TS>
struct variant
{
typedef variant_helper<TS> helper;
char raw_data[helper::size];
}
tagged union
具有标签属性的union:
struct t_union
{
enum {t_int, t_bool, t_float} type_id;
union
{
int as_int;
bool as_bool;
float as_float;
}
}
u_union u;
u.as_int = 10;
u.type_id = t_union::t_int;
模板的特化
template<class Type>
class Null;
template<>
class Null<int>
{
public:
Null() {}
operator int() const
{
return int(std::numeric_limits<int>::max());
}
}
template<>
class Null<size_t>
{
public:
Null() {}
operator size_t() const
{
return size_t(numeric_limits<size_t>::max());
}
}
template<>
class Null<double>
{
public:
Null(){}
operator double() const
{
return double(numeric_limits<double>::max());
}
}
客户端代码:
class AttrValue
{
public:
typedef boost::variant<int, double> value_type;
// Null<>类实例用于一种初始化的动作
// 类的构造函数初始化参数列表可展开为:
// value_ = Null<size_t>(); // 会显式地调用其类型转换运算符函数重载
AttrValue():value_(Null<size_t>()) {}
private:
value_type value_;
}