iNFINITEi
iNFINITEi

Reputation: 1534

How to check a type ignoring its template parameters

How do I determine the class type while ignoring its template parameters.

so for a fully specified type like MyClass<param1, param2, ...>, I want to check if it is indeed a MyClass type?

something in the spirit of

typedef ClassName<param1, param2, ...> T;

//Now my program receives T which can be any arbitrary type
//and I want to have something like the following
//check_if_MyClassType<T>::value should be true
//check_if_MyClassType<int>::value should be false
//check_if_MyClassType<T>::value should be false if T is not a MyClass type e.g T = vector<int>

Upvotes: 0

Views: 106

Answers (2)

R Sahu
R Sahu

Reputation: 206577

I think this is what you are looking for.

#include <iostream>
#include <vector>

template <typename T>
struct IsMyClassType { static const bool value = false; };

template <typename T> struct MyClass {};

template <typename T>
struct IsMyClassType<MyClass<T> > { static const bool value = true; };

Testing the above code...

int main()
{
   std::cout << IsMyClassType<int>::value << std::endl;
   std::cout << IsMyClassType<MyClass<int> >::value << std::endl;
   std::cout << IsMyClassType<MyClass<float> >::value << std::endl;
   std::cout << IsMyClassType<MyClass<std::vector<float> > >::value << std::endl;

   return 0;
}

Output:

0
1
1
1

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119164

template <class T>
struct IsClassName { static const bool value = false; };

template <class param1, param2, ...>
struct IsClassName<ClassName<param1, param2, ...> > { static const bool value = true; };

Upvotes: 3

Related Questions