如何提取__VA_ARGS__? [英] How to extract __VA_ARGS__?

查看:437
本文介绍了如何提取__VA_ARGS__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宏,可以为每个args调用静态函数。

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

这是 实时示例

这篇关于如何提取__VA_ARGS__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆