Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 915
Phil-ZXX Avatar asked Dec 21 '19 16:12

Phil-ZXX


People also ask

Is specialization of template C++?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What is template argument in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is the difference between class template and template class?

A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.

Can default argument be used with the template class?

Can default arguments be used with the template class? Explanation: The template class can use default arguments.


1 Answers

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

like image 199
Jarod42 Avatar answered Oct 18 '22 23:10

Jarod42