2010-12-04 25 views
7

¿Cómo comprobar utilizando alguna plantilla para hackear si un argumento de plantilla aprobado es del tipo de clase?Comprobando si un argumento de plantilla es de un tipo de clase?

Ejemplo

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 
} 
+0

¿Por qué lo necesita saber? –

Respuesta

7

SFINAE debe hacer su trabajo

#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 
+0

@Saurav: Línea 7: error C2056: expresión ilegal – bjskishore123

+0

@UpVoter: Oh ideone compiló el código en modo C++ 0x. Actualicé mi respuesta (para C++ 03). –

+0

¡Guau! Necesito descubrir cómo funciona realmente el código. Gracias. – NEWBIE

2

C++ 0x ofrece una solución muy simple:

#include <iostream> 
#include <type_traits> 

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

Código que también se compila con MSVC++ 08, así como con GCC, Comeau y Clang (editado).

#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 ... ¿podría por favor compilar esto en Comeau, y Clang ... y dime si se compila o no? ¡Gracias!

+0

Sí, eso se compila en aquellos :-) –

Cuestiones relacionadas