我尝试使用 std::conditional_t
来定义类 A
的 typedef
依赖于它的模板参数 T
:
template< typename T >
class A
{
public:
typedef std::conditional_t< std::is_fundamental<T>::value, T, decltype(std::declval<T>().foo())> type;
};
template< typename T >
class B
{
public:
T foo()
{
// ...
}
};
int main()
{
typename A< int >::type a = 5; // causes an error
typename A< B<int> >::type b = 5; // does not cause an error
return 0;
}
不幸的是,代码无法编译。错误:
error: member reference base type 'int' is not a structure or union
typedef std::conditional_t< std::is_fundamental<T>::value, T, decltype(std::declval<T>().foo())> type;
有人知道怎么解决吗?
最佳答案
条件表达式中的两种类型都必须有效,这不是 SFINAE 上下文。
您可以通过仅“执行”所选的类模板来实现您想要的:
typedef typename std::conditional_t< std::is_fundamental<T>::value, identity<T>, foo_t<T>>::type type;
定义为:
template<typename T>
struct identity{ using type = T; };
template<typename T>
struct foo_t{ using type = decltype(std::declval<T>().foo()); };
关于c++ - 使用 `std::conditional_t` 根据其模板参数定义类的 `typedef`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529543/