前言
下面记录几个,在c++元编程中常用的工具类。
Hollow Types
instance_of
代码
struct instance_of
{typedef T type;instance_of(int = 0){}
};const instance_of<int> I_INT = instance_of<int>(); // 这种写法有点繁琐
const instance_of<double> I_DOUBLE = 0; // 使用这种写法
// also fine.
作用
快速创建一个global对象,立刻初始化。
empty
代码
struct empty
{empty() {}
};
// const empty EMPTY; 这种写法可能会报 unused的警告
const empty EMPTY = 0;
作用
用该类表示空。
Selector
代码
template <bool PARAMETER>
struct selector
{
};
typedef selector<true> true_type1;
typedef selector<false> false_type;
作用
可以作为类型参数来做偏特化选择。
Static Value
代码
template <typename T, T VALUE>
struct static_parameter
{
};
template <typename T, T VALUE>
struct static_value : static_parameter<T, VALUE>
{static const T value = VALUE;operator T () const{return VALUE;}static_value(int = 0){}
};//将static转为非static ,更安全
template <typename T, T VALUE>
inline T static_value_cast(static_value<T, VALUE>) //不需要用到形参,所以可以不用定义形参名
{
return VALUE;
};int main() {auto a = static_value_cast(static_value<int, 3>());std::cout << a << "\n";
}
作用
快速创建一个static对象