网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 电子/半导体 > 嵌入式技术 >

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

时间:2023-03-06 09:37

人气:

作者:admin

标签:

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

最近发现了一个有意思的特性: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和模板优先找特化去匹配的特性,估计大家应该看示例代码就能明白。





审核编辑:刘清

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信