Check if object is instance of class with template

5k Views Asked by At

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?
3

There are 3 best solutions below

3
On BEST ANSWER

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

1
On

in c++ you can use

if(typeid(obj1)==typeid(ob2))//or typeid(obj1)==classname
  cout <<"obj1 is instance of yourclassname"

in your case you can check that with typeid(obj1)==std::array

0
On

Below is a shorter version of the solution proposed by max66 that no longer uses struct isArray.
It works in C++98 and later revisions.

#include <string>
#include <vector>
#include <iostream>

template <typename T>
struct Array
{ 
   std::vector<T> v;

   void add (T const t)
    { v.push_back(t); }
};

template <typename T>
constexpr bool isArrayFunc (T const &)
{ return false; }

template <typename T>
constexpr bool isArrayFunc (Array<T> const &)
{ return true; }

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
}