// 使用 static 特性进行常量存储
template<typename _Tp, _Tp __v>
struct integral_constant
{
static constexpr _Tp value = __v;
using value_type = _Tp;
using type = integral_constant<_Tp, __v>;
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; }
};
template<typename _Tp, _Tp __v>
constexpr _Tp integral_constant<_Tp, __v>::value;
// 重要存储 bool 常量
//type_traits 中等同于 bool 类型
using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;
template<bool B>
using bool_constant = integral_constant<bool, B>;
创建一个静态 _Tp 类型的 value 变量, 并进行初始化
原理: 由于static成员可以通过类型进行访问, 因此 type_traits文件 是编译期工具, true_type 和false_type 是所有类的基础. 举例:
int main(){
//没有创建具体实例, 直接使用类型进行访问 value
std::cout << integral_constant<int, 3>::value << std::endl;
}
提供 type 接口, 以便其他模板进行使用
type 接口是返回模板的具体类型, 以便于其他模板进行使用
功能类似于普通函数中的 return , 因为在 type_traits 中我们总需要知道类型信息
// 详情见 is_reference 类
template<typename _Tp>
struct is_reference
: public __or_< is_lvalue_reference<_Tp>,
is_rvalue_reference<_Tp>>::type
{ };
提供两个 operator 函数
constexpr operator value_type() const noexcept { return value; } 提供类型的隐式转换, 可以将 integral_constant 对象赋值给 _Tp 对象constexpr value_type operator()() const noexcept { return value; } 提供仿函数接口, 实现 integral_constant 对象() 的调用功能, 以便访问 value 的值class test{};
int main(){
std::cout << "integral_constant test: " << std::endl;
bool test1;
mySTL::true_type t_type;
test1 = t_type;
std::cout << test1 << std::endl;
mySTL::false_type f_type;
test1 = f_type;
std::cout << test1 << std::endl;
bool test2 = t_type();
std::cout << test2 << std::endl;
test2 = f_type();
std::cout << test2 << std::endl;
mySTL::integral_constant<int, 5> intConstant;
int a = intConstant();
int b = intConstant;
std::cout << a << " " << b << std::endl;
return 0;
}