最近发现了一个有意思的特性: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 {};
比如判断某个类是否可迭代:
templateconstexpr bool is_iterable{}; template constexpr bool is_iterable ().begin()), decltype(std::declval ().end())>> = true;
比如判断某个类是否有某个函数:
templatestruct 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和模板优先找特化去匹配的特性,估计大家应该看示例代码就能明白。
审核编辑:刘清
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。
举报投诉
-
编译器
+关注
关注
1文章
1669浏览量
51073 -
C++语言
+关注
关注
0文章
147浏览量
7583
原文标题:C++17一个很冷门很有意思的新特性
文章出处:【微信号:C语言编程,微信公众号:C语言编程】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录
相关推荐
热点推荐
【设计技巧】rtos的核心原理简析
rtos的核心原理简析rtos全称real-time operating system(实时操作系统),我来简单分析下:我们都知道,c语句中调用一个
发表于 07-23 08:00
OpenHarmony智慧设备开发-芯片模组简析T507
降噪,自动调色系统和梯形校正模块可以提供提供流畅的用户体验和专业的视觉效果。
典型应用场景:
工业控制、智能驾舱、智慧家居、智慧电力、在线教育等。
、*附件:OpenHarmony智慧设备开发-芯片模组简析T507.docx
发表于 05-11 16:34
a17和a16的参数区别
哪些重要的区别呢?本文将一一探讨。 1. 内核改进 C++17引入了一些内核改进,其中最显着的是对字符串的内存使用的优化。在C++16的版中,字符串引用传递时,会发生大量的无效副本拷贝
C++ invoke与function的区别在哪?
invoke是C++17标准引入的一个函数模板,用来调用可调用对象(Callable Object,如函数指针、函数对象、成员函数指针等)并返回结果。

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