如何提取 __VA_ARGS__?

2022-01-11 00:00:00 macros templates c++ c++11

我有一个宏来为每个参数调用静态函数.

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

例如:

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

我的问题是我需要使用带有可变数量参数的 foo,是否可以使用 __VA_ARGS__ ?

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

如下一行:

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

谢谢

推荐答案

宏扩展不像使用可变参数模板的参数包扩展那样工作.您所拥有的将扩展为:

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

X,Y::do();

而不是

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

如你所愿.但在 C++11 中,您可以使用可变参数模板.例如,你可以这样做:

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

这是一个现场示例.

相关文章