在此之前,先来回顾元编程当中的一个重要概念。- template<typename _Tp, _Tp __v>
- struct integral_constant
- {
- static constexpr _Tp value = __v;
- typedef _Tp value_type;
- typedef integral_constant<_Tp, __v> type;
- constexpr operator value_type() const noexcept { return value; }
- #if __cplusplus > 201103L
- #define __cpp_lib_integral_constant_callable 201304L
- constexpr value_type operator()() const noexcept { return value; }
- #endif
- };
- /// The type used as a compile-time boolean with true value.
- using true_type = integral_constant<bool, true>;
- /// The type used as a compile-time boolean with false value.
- using false_type = integral_constant<bool, false>;
复制代码 std::true_type和std::false_type其实就是std::integral_constant传入模板特定参数的情形,注意到integral_constant结构体当中的value_type,顾名思义指的是值的类型,对应到std::true_type和std::false_type就是true和false。
先尝试着来写一个对std::vector的判断。
[code]// vectortemplate struct is_vector : std::false_type{};template struct is_vector : std::true_type{};template bool is_vector_v = is_vector::value;int main() { std::vector v1; std::vector v2; std::vector v3; std::cout |