[英]How to specialize a type based on whether a template parameter has an alias
I want to be able to specialize a type based on whether a container has a specified typedef for example 我希望能够基于例如容器是否具有指定的typedef来专门化类型
class SomethingElse {};
class Something {
using Type = int;
};
static constexpr bool value = ChooseIfType<Something>::value;
Is there a way for ChooseIfType
to return false when the type does not have the typedef Type
? 当类型没有typedef
Type
时, ChooseIfType
可以返回false?
I feel like there is an easy way to do this but I cannot figure it out. 我觉得有一个简单的方法可以做到这一点,但我无法弄清楚。
Thanks! 谢谢!
Just use std::void_t
(or a C++11 alternative): 只需使用
std::void_t
(或C ++ 11替代品):
template<typename T, typename = std::void_t<>>
struct ChooseIfType : std::false_type {};
template<typename T>
struct ChooseIfType<T, std::void_t<typename T::Type>> : std::true_type {};
The solution makes use of SFINAE. 该解决方案利用了SFINAE。 The default is never malformed and creates a trait with value false.
默认值永远不会格式错误,并创建一个值为false的特征。 The compiler tries to match all template specializations (only one in this case).
编译器尝试匹配所有模板专业化(在这种情况下,只有一个)。 If
T
has a member type Type
, then ChooseIfType<T, void_t<typename T::Type>>
is more specialized than ChooseIfType<T, void_t<>>
. 如果
T
具有成员类型Type
,则ChooseIfType<T, void_t<typename T::Type>>
比ChooseIfType<T, void_t<>>
更专门。 If it doesn't, then it's not a viable specialization and the default is selected, but Substitution Failure Is Not An Error. 如果不是,则说明它不是可行的专业化,并且选择了默认值,但“替换失败不是错误”。
as per cppreference, a C++11 void_t
implementation could look like this: 根据cppreference,C ++ 11
void_t
实现可能如下所示:
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.