简体   繁体   English

如何根据模板参数是否具有别名来专门化类型

[英]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 {};

live demo 现场演示

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.

相关问题 根据是否存在特定成员来专门化模板 - Specialize template based on whether a specific member exists 如何专门化具有指向成员参数的指针的模板类? - How to specialize a template class which has a pointer to member parameter? 如何专门针对参数列表中的类型使用模板功能 - How can I specialize template function for a type in Parameter lists C ++ 11`using`关键字:specialize模板参数的模板别名 - C++11 `using` keyword: specialize template alias of template parameter 如何使用模板模板参数专门化类模板? - How to specialize a class template with a template template parameter? 使用非类型模板参数专门化模板模板参数 - Specialize template template parameter with a non-type template parameter 是否可以根据模板类型参数的嵌套typedef的存在来专门化模板定义? - Is it possible to specialize a template definition based on the existence of a nested typedef of a template type parameter? 如何为一个类专门化模板template参数? - How to specialize template template parameter for a class? 基于 *inner* 类型的智能指针专门化模板 - Specialize template based on *inner* type of a smart pointer 如何专门化具有多个参数的功能模板? - How to specialize a function template with more than 1 parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM