简体   繁体   English

检查类是否具有模板特化(使用 bool 或 int 等模板参数)

[英]Check if class is of template specialization (with template arguments like bool or int)

Based on the answers from How to tell if template type is an instance of a template class?基于如何判断模板类型是否是模板类的实例? and Check if class is a template specialization?检查类是否是模板专业化? I created the following variant to check for specific instantiations of MyClass1 , MyClass2 or MyClass3 :我创建了以下变体来检查MyClass1MyClass2MyClass3特定实例:

template <class T, template <class...> class Template>
constexpr bool is_instance_of_v = false;

template <template <class...> class Template, class... Args>
constexpr bool is_instance_of_v<Template<Args...>, Template> = true;

template<class T> struct MyClass1 { };
template<class T, class B> struct MyClass2 { };
template<class T, bool B> struct MyClass3 { };


int main(int argc, char* argv[])
{
    constexpr bool b1 = is_instance_of_v<MyClass1<float>, MyClass1>;
    constexpr bool b2 = is_instance_of_v<MyClass1<float>, MyClass2>;
    // constexpr bool b3 = is_instance_of_v<MyClass1<float>, MyClass3>;  // <-- does not compile

    return 0;
}

However, the code for b3 does not compile & gives the following error:但是, b3的代码无法编译并出现以下错误:

error C3201: the template parameter list for class template 'MyClass3' does not match the 
                 template parameter list for template parameter 'Template'
error C2062: type 'unknown-type' unexpected

It seems this is because the bool argument from MyClass3 is not a class , and thus cannot be captured via template <class...> class Template .这似乎是因为来自MyClass3bool参数不是class ,因此无法通过template <class...> class Template捕获。

Is there a way to fix this so that it works for any list of template arguments (not just class , but also bool , int , etc.)?有没有办法解决这个问题,以便它适用于任何模板参数列表(不仅是class ,还有boolint等)?

没有通用模板来处理类型参数和非类型参数(和模板模板参数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM