The same name macro with different arguments

10,307

Solution 1

It is not possible.
A symbol name cannot be redefined. Unlike functions macros cannot be overloaded. Think of it logically macros are for pure textual replacement, So how can you replace two different things for the same entity?

An alternative and better solution:
You can write a inline function for achieving the same result. It provides you additional advantage of type checking and saves you from the murky side effects of macros.

Solution 2

This would work.

#define FI(value, ...) FI_(value, ##__VA_ARGS__, 2, 1)
#define FI_(value, level, n, ...) FI##n(value, level)
#define FI1(value, ...) do {l << value; Doit(l);} while (0)
#define FI2(value, level) do {l << value; Doit(l, level);} while (0)

Solution 3

Actually it is possible. However, it will result in compiler warning regarding redefinition.

See this for more details: http://efesx.com/2010/08/31/overloading-macros/

Solution 4

This is a situation in which you really should use inline functions. Knowing nothing about the types you are using, a possible implementation might look like this:

template<typename T>
inline void fi(T & l, const T & value) {
   l << value;
   Doit(l);
}

template<typename T>
inline void fi(T & l, const T & value, const T & level) {
   l << value;
   Doit(l, level);
}

If you ever encounter a situation in which you have to stick to macros, you will have to work-around this limitation that they can't be overloaded, at least not per the standard. To "overload" them, we just write the number of arguments on the name of the macro, which is a common way to do so (in fact, even the OpenGL library uses this method to "overload" C functions).

#define FI1(value) do {l<<value;  Doit(l); } while(0)
#define FI2(value, level) do {l<<value ; Doit(l,level); } while(0)
Share:
10,307

Related videos on Youtube

vico
Author by

vico

Updated on September 15, 2022

Comments

  • vico
    vico over 1 year

    Is it possible to have 2 macros with the same name, but different arguments? Something like this:

    #define FI(value) do {l<<value;  Doit(l); } while(0)
    #define FI(value, level) do {l<<value ; Doit(l,level); } while(0)
    
    • Puppy
      Puppy over 11 years
      Yes, it's called "Inline functions".
    • leemes
      leemes over 11 years
      @FredOverflow I know. But (1) there are still cases in which custom loops are nice, (2) there are compilers out there which don't yet fully support C++11. I think there are some libraries we want to still support older compilers, even in the next couple of years. :)
  • Tadeusz Kopec for Ukraine
    Tadeusz Kopec for Ukraine over 11 years
    One definition rule has nothing to do with preprocessor macros. And you can redefine macro provided you used #undef before.
  • Alok Save
    Alok Save over 11 years
    @TadeuszKopec: You are correct. Macros are evaluated at preprocessing and the compiler, which implements ODR never sees any macro.