Is there a way to compile time if the variable is a class, structure, or base type in C ++?
I am trying to implement a templating class that could tell me if a variable is a class, structure, or base type.
So far I have come up with this:
template< typename T >
class is_class
{
private:
template< typename X >
static char ( &i_class( void(X::*)() ) )[1];
//
template< typename X >
static char ( &i_class( X ) )[2];
public:
static bool const val = sizeof( i_class< T >(0) ) == 1;
};
and ussage:
is_class< int >::val; // false
is_class< some_class_type >::val; // true
The problem is that now I need to write an empty void function in every class that could be used with this code.
Does anyone know a solution to this problem?
a source to share
is_class
is a member of the Boost.Type_Traits library. The implementation is probably similar to what you already have. You should use in conjunction with enable_if
to create a function if needed:
template <class T>
typename enable_if_c<boost::is_class<T>::value>::type
foo() { }
Or the equivalent:
template <class T>
typename enable_if<boost::is_class<T>>::type
foo() { }
The function is foo
generated only if the type T
is of the class type.
The return value for the function, if generated, is the second parameter (omitted) to the template enable_if
(which is by default void
).
a source to share
If it's only statement at compile time, you can use BOOST_STATIC_ASSERT
and Boost.TypeTraits , to test whether the types of fit. If you want to enable the template for certain types, you might have success with Boost enable_if .
a source to share