最近发现了一个有意思的特性: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和模板优先找特化去匹配的特性,估计大家应该看示例代码就能明白。
审核编辑:刘清
全部0条评论
快来发表一下你的评论吧 !