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 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.
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.
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 arguments be used with the template class? Explanation: The template class can use default arguments.
There are no common templates to handle type parameters and non type parameters (and template template parameters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With