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

Viewed 541

How do I check if a variable is a template class without knowing the template argument, so in the example below, how do I determine (prove) that A<int> is an A.

template <class T>
class A {/*----*/};

int main() {
    auto a1 = A<int>();
    bool is_a1_an_A = some_method(a1, A);
}

Any help is greatly appreciated. Thanks!

1 Answers

This is pretty straightforward using a specialized helper class:

#include <type_traits>
#include <iostream>

template<typename T> class A {};

template<typename T>
struct is_a : std::false_type {};

template<typename T>
struct is_a<A<T>> : std::true_type {};


int main()
{
    auto a1=A<int>{};

    bool b1=false;

    std::cout << is_a<decltype(a1)>::value << std::endl;

    std::cout << is_a<decltype(b1)>::value << std::endl;
    return 0;
}

is_a gets specialized for a template parameter that's any instance of A. The non-specialized version is the false trait, and the specialized version is the true trait, and that's pretty much it. If you are not familiar with the topic of template specialization, this is a fairly involved and deep topic that should have a full explanation in every good C++ textbook, and I refer you there for a full and complete discussion on this topic.

Related