NEWBIE
NEWBIE

Reputation: 53

Checking whether a template argument is of a class type?

How to check using some template hack whether a template argument passed is of class type?

Example

int main()
{
   CheckIfClass<int>::checkConst ; No it is not of a class type
   class CLASS{};
   CheckIfClass<CLASS>::checkConst ; Yes CLASS is a class.
   CheckIfClass<std::string>::checkConst ; Yes std::string is a class
}

Upvotes: 5

Views: 1710

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361412

Code that compiles with MSVC++08 ALSO, as well as with GCC, Comeau, and Clang (edited).

#include <iostream>
template<typename T>
struct Check_If_T_Is_Class_Type
{
    template<typename C> static char func (char C::*p);
    template<typename C> static int func (...);
    enum{val = sizeof (func<T>(0)) == 1};
};
class empty{};
int main()
{   
    std::cout<<Check_If_T_Is_Class_Type<empty>::val; // 1
    std::cout<<Check_If_T_Is_Class_Type<int>::val; // 0
    std::cout<<Check_If_T_Is_Class_Type<std::string>::val; //1
}

@Prasoon... could you please compile this on Comeau, and Clang ... and tell me if it gets compiled or not? thanks!

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263128

C++0x offers a very simple solution:

#include <iostream>
#include <type_traits>

int main()
{
    std::cout << is_class< your_type_here >::value << std::endl;
}

Upvotes: 2

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

SFINAE should do your job

#include <iostream>
template<typename T>
struct Check_If_T_Is_Class_Type
{
    template<typename C> static char func (char C::*p);
    template<typename C> static int func (...);
    enum{val = sizeof (Check_If_T_Is_Class_Type<T>::template func<T>(0)) == 1};
};
class empty{}; // Defined the class in the global namespace. 
               // You can't have local classes as template arguments in C++03

int main()
{

    std::cout<<Check_If_T_Is_Class_Type<empty>::val; // 1
    std::cout<<Check_If_T_Is_Class_Type<int>::val; // 0
    std::cout<<Check_If_T_Is_Class_Type<std::string>::val; //1
}

Output

101

Upvotes: 7

Related Questions