简体   繁体   中英

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 :

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:

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 .

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.)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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