前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++17一个很冷门很有意思的新特性

C++17一个很冷门很有意思的新特性

作者头像
范蠡
发布2022-07-01 14:11:52
6010
发布2022-07-01 14:11:52
举报

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

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

代码语言:javascript
复制
template< class... >using void_t = void;

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

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

代码语言:javascript
复制
template <class, class = std::void_t<>>struct has_type : std::false_type {};
template <class T>struct has_type<T, std::void_t<typename T::type>> : std::true_type {};

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

代码语言:javascript
复制
template <class, class = std::void_t<>>struct has_a_member : std::false_type {};
template <class T>struct has_a_member<T, std::void_t<decltype(std::declval<T>().a)>> : std::true_type {};

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

代码语言:javascript
复制
template <typename, typename = void>constexpr bool is_iterable{};
template <typename T>constexpr bool is_iterable<T, std::void_t<decltype(std::declval<T>().begin()), decltype(std::declval<T>().end())>> = true;

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

代码语言:javascript
复制
template <class T, class = void>struct has_hello_func : std::false_type {};
template <class T>struct has_hello_func<T, std::void_t<decltype(std::declval<T>().hello())>> : std::true_type {};

测试结果:

代码语言:javascript
复制
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<HasType>::value << '\n';   // 1  std::cout << has_type<NHasType>::value << '\n';  // 0
  std::cout << has_a_member<Hasa>::value << '\n';   // 1  std::cout << has_a_member<NHasa>::value << '\n';  // 0
  std::cout << has_hello_func<HasHello>::value << '\n';    // 1  std::cout << has_hello_func<NoHasHello>::value << '\n';  // 0
  std::cout << is_iterable<std::vector<double>> << '\n';  // 1  std::cout << is_iterable<double> << '\n';               // 0}

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

推荐阅读

代码语言:javascript
复制
如果想加入 高质量 C++ 微信交流群 进行交流,可以先加我微信 easy_coder,备注"加微信群",我拉你入群,备注不对不加哦

如有收获,点个在看,诚挚感谢

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-07-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 高性能服务器开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云服务器
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档