C++17引入的一个新特性void_t简析

描述

最近发现了一个有意思的特性:void_t。

void_t是C++17引入的一个新特性,它的定义很简单(有些编译器的实现可能不是这样,但也大体类似):

 

template< class... >
using void_t = void;

 

看着它很简单,但它搭配SFINAE却可以在模板元编程中发挥巨大作用。

比如在编译期判断类是否有某个类型using:

 

template >
struct has_type : std::false_type {};


template 
struct has_type> : std::true_type {};

 

比如判断是否有某个成员:

 

template >
struct has_a_member : std::false_type {};


template 
struct has_a_member().a)>> : std::true_type {};

 

比如判断某个类是否可迭代:

 

template 
constexpr bool is_iterable{};


template 
constexpr bool is_iterable().begin()), decltype(std::declval().end())>> = true;

 

比如判断某个类是否有某个函数:

 

template 
struct has_hello_func : std::false_type {};


template 
struct has_hello_func().hello())>> : std::true_type {};

 

测试结果:

 

struct HasType {
  typedef int type;
};
struct NHasType {
  int hello;
};


struct Hasa {
  int a;
};
struct NHasa {
  int b;
};


struct HasHello {
  void hello();
};
struct NoHasHello {};


int main() {
  std::cout << has_type::value << '
';   // 1
  std::cout << has_type::value << '
';  // 0


  std::cout << has_a_member::value << '
';   // 1
  std::cout << has_a_member::value << '
';  // 0


  std::cout << has_hello_func::value << '
';    // 1
  std::cout << has_hello_func::value << '
';  // 0


  std::cout << is_iterable> << '
';  // 1
  std::cout << is_iterable << '
';               // 0
}

 

它的原理其实就是利用SFINAE和模板优先找特化去匹配的特性,估计大家应该看示例代码就能明白。





审核编辑:刘清

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分