Phil-ZXX
Phil-ZXX

Reputation: 3275

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

Upvotes: 6

Views: 332

Answers (1)

Jarod42
Jarod42

Reputation: 218193

There are no common templates to handle type parameters and non type parameters (and template template parameters).

Upvotes: 3

Related Questions