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?

+1


a source to share


3 answers


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

).

+8


a source


Use boost type properties .



0


a source


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 .

0


a source







All Articles