Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check type on compile time

I'm giving option to compile the program with either float or double type, but there is a problem: I need to manually set either GL_FLOAT or GL_DOUBLE, because I dont know how can I 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 dont have C++11 or whatsoever, just the good old C++.

like image 471
Rookie Avatar asked Jun 06 '12 11:06

Rookie


People also ask

Are templates compile-time or runtime?

All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!

Are C++ templates compile-time?

7.2.The C++ compiler uses compile-time instantiation, which forces instantiations to occur when the reference to the template is being compiled.

Is template a compile-time mechanism?

Templates are the feature that supports generic programming in C++, which are compile time mechanism and there is no runtime overhead associated with using them.


1 Answers

In C++11, you can use std::conditional and std::is_same as:

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

In C++03, you can implement these functionalities yourself as:

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; };

and

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; };

Note that the implementation of conditional is taken from the site itself.

like image 194
Nawaz Avatar answered Sep 28 '22 01:09

Nawaz