conditional_t和enable_if_t的实现

发布时间 2023-10-05 19:59:41作者: ChebyshevTST

  conditional_t和enable_if_t是元编程里面很相似却有有着一定区别的模板。形如conditional_t<_Cond, _If, _Else>是指如果_Cond表达式为true,则类型为_If,否则类型为_Else。而形如enable_if_t<_Cond, _Tp>是指如果_Cond表达式为true,则类型为_Tp,否则不定义类型。

 

conditional_t的标准实现

template<bool>
    struct __conditional
    {
      template<typename _Tp, typename>
	using type = _Tp;
    };

  template<>
    struct __conditional<false>
    {
      template<typename, typename _Up>
	using type = _Up;
    };

  // More efficient version of std::conditional_t for internal use (and C++11)
  template<bool _Cond, typename _If, typename _Else>
    using __conditional_t
      = typename __conditional<_Cond>::template type<_If, _Else>;

这里指出一点,最后一行::后面的template其实可以去掉,变成::type<_If, _Else>。

 

enable_if_t的实现

template<bool, typename _Tp = void>
    struct enable_if
    { };

  // Partial specialization for true.
  template<typename _Tp>
    struct enable_if<true, _Tp>
    { typedef _Tp type; };

  // __enable_if_t (std::enable_if_t for C++11)
  template<bool _Cond, typename _Tp = void>
    using __enable_if_t = typename enable_if<_Cond, _Tp>::type;

对true类型进行了特化,只有true的时候才定义类型,否则不定义任何类型。_Tp的默认缺省类型是void。

 

  关于enable_if_t的简单应用,在之前的C++系列里面也有提到过。