使用`std :: conditional_t`根据其模板参数定义类'typedef` [英] Using `std::conditional_t` to define a class' `typedef` in dependence of its template parameter
本文介绍了使用`std :: conditional_t`根据其模板参数定义类'typedef`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 std :: conditional_t
定义类 A
的 typedef
取决于其模板参数 T
:
I try to use std::conditional_t
to define a class A
's typedef
in dependence of its template parameter 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;
}
不幸的是,代码无法编译。错误:
Unfortunately, the code does not compile. Error:
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上下文。
Both types in the conditional expression must be valid, this isn't a SFINAE context.
仅通过执行所选的类模板即可实现所需的目标:
You can achieve what you want by "executing" only the chosen class template:
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()); };
这篇关于使用`std :: conditional_t`根据其模板参数定义类'typedef`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文