Search code examples
c++classtemplatestypechecking

Check if object is instance of class with template


My class:

template < typename T >
Array<T>{};

(Source data is stored in vector)

I have an object:

Array< string > a;
a.add("test");

And I have an object:

Array< Array< string > > b;
b.add(a);

How can I check:

  1. Is b[0] an instance of Array (regardless of template type)?
  2. Is a[0] an instance of any type except Array?

Solution

  • If you can use C++11, creating your type traits; by example

    #include <string>
    #include <vector>
    #include <iostream>
    #include <type_traits>
    
    template <typename T>
    struct Array
     { 
       std::vector<T> v;
    
       void add (T const t)
        { v.push_back(t); }
     };
    
    template <typename>
    struct isArray : public std::false_type
     { };
    
    template <typename T>
    struct isArray<Array<T>> : public std::true_type
     { };
    
    template <typename T>
    constexpr bool isArrayFunc (T const &)
     { return isArray<T>::value; }
    
    
    int main()
     {
       Array<std::string> a;
       Array<Array<std::string>> b;
    
       a.add("test");
       b.add(a);
    
       std::cout << isArrayFunc(a.v[0]) << std::endl; // print 0
       std::cout << isArrayFunc(b.v[0]) << std::endl; // print 1
     }
    

    If you can't use C++11 or newer but only C++98, you can simply write isArray as follows

    template <typename>
    struct isArray
     { static const bool value = false; };
    
    template <typename T>
    struct isArray< Array<T> >
     { static const bool value = true; };
    

    and avoid the inclusion of type_traits

    --- EDIT ---

    Modified (transformed in constexpr) isArrayFunc(), as suggested by Kerrek SB (thanks!).