Search code examples
c++templatestype-traits

How to check if an object is an instance of a template class of multiple template arguments in C++?


I have the following class:

template <typename T, typename U = UDefault>
class A;

How to check whether types such as A<float> or A<float, int> are instances of the above templated class?

I tried modifying How to check if an object is an instance of a template class in C++? into:

template <typename T, typename U>
struct IsA : std::false_type
{};

template <typename T, typename U>
struct IsA<A<T, U>> : std::true_type
{};

but it's giving the following error

20:18: error: wrong number of template arguments (1, should be 2)
16:8: error: provided for 'template<class T, class U> struct IsA'
 In function 'int main()':
40:34: error: wrong number of template arguments (1, should be 2)
16:8: error: provided for 'template<class T, class U> struct IsA'

How can this be solved?


Solution

  • Your IsA class should be expected to take one template argument. The type you are testing.

    template <typename Type>
    struct IsA : std::false_type {};
    
    template <typename T, typename U>
    struct IsA< A<T,U> > : std::true_type {};
    //          ^^^^^^ The specialization of your one template argument.
    

    Or put alternately, since the individual template parameters to A do not matter here:

    template <typename ...AParams>
    struct IsA< A<AParams...> > : std::true_type {};
    //          ^^^^^^^^^^^^^ The specialization of your one template argument.
    

    See it work in Compiler Explorer