Macro overload with variable arguments

I am trying to create a macro Mthat will expand to one of two possibilities, based on whether it has one or more arguments:

M(x)

should expand to

f(x)

While

M(x, "%d%d%d", 1, 2, 3)

should expand to

g(x, "%d%d%d", 1, 2, 3)

If function signatures

f(int x);
g(int x, const char *fmt, ...);

various answers regarding macro overloading if the number of arguments is known; however, their length determination methods __VA_ARGS__only work with a finite number selected.

Is there any trick that could do a similar approach for my case of "one argument / more than one argument"?

Note:

Function overloading is not an option, because in my case they are actually constructors for two different classes.

+4
1

Simple. , , 1:

#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__

#define CHECK_N(x, n, ...) n
#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)
#define PROBE(x) x, 1,

#define IS_1(x) CHECK(PRIMITIVE_CAT(IS_1_, x))
#define IS_1_1 PROBE(~)

, IS_1 1, 1, 0. , ( 8):

#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)

, 1 :

#define M_1 f
#define M_0 g

#define M(...) CAT(M_, IS_1(NARGS(__VA_ARGS__)))(__VA_ARGS__)

, M :

M(x) // Expands to f(x)
M(x, "%d%d%d", 1, 2, 3) // Expands to g(x, "%d%d%d", 1, 2, 3)

64 ( 8), C (gcc 32767 ). , , . :

#define TO_ARGS(seq) TO_ARGS_END(TO_ARGS_1 seq)
#define TO_ARGS_END(...) TO_ARGS_END_I(__VA_ARGS__)
#define TO_ARGS_END_I(...) __VA_ARGS__ ## _END
#define TO_ARGS_1(x) x TO_ARGS_2  
#define TO_ARGS_2(x) , x TO_ARGS_3  
#define TO_ARGS_3(x) , x TO_ARGS_2  
#define TO_ARGS_1_END
#define TO_ARGS_2_END
#define TO_ARGS_3_END

M, , :

#define IS_PAREN(x) CHECK(IS_PAREN_PROBE x)
#define IS_PAREN_PROBE(...) PROBE(~)

#define EAT(...)

#define M_1(seq) g(TO_ARGS(seq))
#define M_0(seq) f(TO_ARGS(seq))

#define M(seq) CAT(M_, IS_PAREN(EAT seq))(seq)

:

M((x)) // Expands to f(x)
M((x)("%d%d%d")(1)(2)(3)) // Expands to g(x, "%d%d%d", 1, 2, 3)

, ++ 14, , variadiac:

template<class T>
auto M(T&& xs) -> decltype(f(std::forward<T>(x)))
{
    return f(std::forward<T>(x));
}

template<class T, class U, class... Ts>
auto M(T&& x, U&& y, Ts&&... xs) -> decltype(g(std::forward<T>(x), std::forward<U>(y), std::forward<Ts>(xs)...))
{
    return g(std::forward<T>(x), std::forward<U>(y),std::forward<Ts>(xs)...);
}

:

class M : f, g
{
    template<class T>
    M(T&& xs) : f(std::forward<T>(x))
    {}

    template<class T, class U, class... Ts>
    M(T&& x, U&& y, Ts&&... xs) : g(std::forward<T>(x), std::forward<U>(y), std::forward<Ts>(xs)...)
    {}
};
+1

All Articles