How to check type at compile time

I give the opportunity to compile a program using a float or double type, but there is a problem: I need to manually set GL_FLOAT or GL_DOUBLE, because I do not know how I can do the following:

typedef float MYTYPE;

#if MYTYPE == float
    #define GL_MYTYPE GL_FLOAT // used for vertex array parameters.
#else
    #define GL_MYTYPE GL_DOUBLE
#endif

Note. I do not have C ++ 11 or even just the good old C ++.

+5
source share
6 answers

You can do it as follows:

#define MYFLOAT

#ifdef MYFLOAT
    typedef float MYTYPE;
     #define GL_MYTYPE GL_FLOAT // used for vertex array parameters.
#else
    typedef double MYTYPE;
    #define GL_MYTYPE GL_DOUBLE
#endif

You will need to determine MYFLOATif you want to use float, or omit it for use double.

PS: keep in ind, this is not evaluated at compile time, but at the time of preprocessing.

+1
source

In C ++ 11, you can use std::conditionaland std::is_samehow:

#define GL_MYTYPE  std::conditional                       \
                   <  std::is_same<MYTYPE,float>::value,  \
                      GL_FLOAT,                           \
                      GL_DOUBLE                           \
                   >::type                            

++ 03 :

template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

template<class T, class U>
struct is_same { static const bool value = false; };

template<class T>
struct is_same<T, T> { static const bool value = true; };

, conditional .

+9

#define . typedef.

+2

, , typedef

#if defined(TYPE_IS_FLOAT)
typedef float MYTYPE;
#else
typedef double MYTYPE;
#end

, TYPE_IS_FLOAT ( , ).

, , , , .

+2

#ifdef :

#ifdef DOUBLE
   #define GL_MYTYPE GL_FLOAT
   //or
   typdef ...
#endif

#ifdef FLOAT
   #define GL_MYTYPE GL_DOUBLE
   //or
   typdef ...
#endif

DOUBLE FLOAT .

0

I think Nawaz's answer is almost correct. In a special case, a choice between GL_FLOATand GL_DOUBLEis std::conditionalnot required. Just use triple if :

#define GL_MYTYPE std::is_same<MYTYPE,float>::value?GL_FLOAT:GL_DOUBLE

This is due to the fact that GL_FLOAT, and GL_DOUBLEare not types, and just GLenumvalues. Therefore GL_MYTYPEalso should not be typename, but GLenum. Therefore, I would prefer to use:

const GLenum GL_MYTYPE = std::is_same<MYTYPE,float>::value?GL_FLOAT:GL_DOUBLE;
0
source

All Articles