【发布时间】:2021-12-17 16:15:35
【问题描述】:
我尝试编写一个模板元函数来测试“T是一个类型有一个成员类型,名为type”。
代码如下:
#include <iostream>
#include <type_traits>
template <typename T, typename E = void>
struct has_type;
// branch 1
template <typename T, typename E>
struct has_type : std::false_type {};
// branch 2
template <typename T>
struct has_type<
T, std::enable_if_t<std::is_same_v<typename T::type, typename T::type>, T>
> : std::true_type {};
struct with_type {using type = void;};
struct without_type {};
int main()
{
std::cout<< has_type< with_type >::value <<std::endl;
std::cout<< has_type< without_type >::value <<std::endl;
return 0;
}
我想,编译器会首先尝试使用分支 2,如果类型T 有成员类型type,我们得到std::true_type。
或者找不到T::type,然后SFINAE并使用分支1,我们得到std::false_type
但是两个输出都是false。
有什么我理解错了吗?
【问题讨论】:
标签: c++ templates metaprogramming