Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if inside #define?

I'm sitting on some legacy code that generates a lot of code through #defines. Now I know it's not possible to have an #ifdef inside a #define, but is an #if possible? I would like to do add some specialization for a specific type. (without making major changes like using templates instead). The following sample gives me cryptic errors so this is not the way:

#define MK_GET(type) \
  type get_ ## type (int index) \
  { \
    #if type == double \  <-- what i want to add
      specialized code... \
    #endif
    ...
  } \

MK_GET(double);
MK_GET(int);
MK_GET(string);
like image 813
Frank Avatar asked Dec 08 '11 08:12

Frank


2 Answers

You could achieve that with templates:

template<typename T>
struct getter
{
    T operator()(int index)
    {
        // general code
    }
};

template<>
struct getter<double>
{
    T operator()(int index)
    {
        // specialized code
    }
};

#define CAT(a, b) a ## b
#define MK_GET(type) type CAT(get_, type) (int index) getter<type>()(index)
like image 189
ronag Avatar answered Sep 30 '22 10:09

ronag


The pre-processor is one pass process, so you can't place macro defines inside of macro defines. The only way to do this is via the template interface.

like image 36
DipSwitch Avatar answered Sep 30 '22 10:09

DipSwitch