Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract __VA_ARGS__?

I hava a macro to call static function for each args.

For example:

#define FOO(X) X::do();
#define FOO_1(X,Y) X::do(); Y::do();

My question is that I need to use foo with variable number of arguments, is it possible to use __VA_ARGS__ ?

Like the line below:

#define FOO(...) __VA_ARGS__::do() ? 

Thanks

like image 226
Kennir Avatar asked Mar 25 '23 02:03

Kennir


1 Answers

Macro expansion does not work like argument pack expansion with variadic templates. What you have will expand to:

X,Y::do();

And not to

X::do(); Y::do();

As you hoped. But in C++11 you could use variadic templates. For instance, you could do what you want this way:

#include <iostream>

struct X { static void foo() { std::cout << "X::foo()" << std::endl; }; };
struct Y { static void foo() { std::cout << "Y::foo()" << std::endl; }; };
struct Z { static void foo() { std::cout << "Z::foo()" << std::endl; }; };

int main()
{
    do_foo<X, Y, Z>();
}

All you need is this (relatively simple) machinery:

namespace detail
{
    template<typename... Ts>
    struct do_foo;

    template<typename T, typename... Ts>
    struct do_foo<T, Ts...>
    {
        static void call()
        {
            T::foo();
            do_foo<Ts...>::call();
        }
    };

    template<typename T>
    struct do_foo<T>
    {
        static void call()
        {
            T::foo();
        }
    };
}

template<typename... Ts>
void do_foo()
{
    detail::do_foo<Ts...>::call();
}

Here is a live example.

like image 140
Andy Prowl Avatar answered Mar 31 '23 12:03

Andy Prowl