conditional_t和enable_if_t的实现

  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++系列里面也有提到过。

posted @   ChebyshevTST  阅读(177)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示