gpt4 book ai didi

c++ - 如何提取__VA_ARGS__?

转载 作者:太空狗 更新时间:2023-10-29 20:14:28 25 4
gpt4 key购买 nike

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

例如:

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

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

喜欢下面这行:

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

谢谢

最佳答案

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

X,Y::do();

而不是

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

如你所愿。但在 C++11 中,您可以使用可变参数模板。例如,您可以通过这种方式执行您想要的操作:

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

您只需要这个(相对简单的)机器:

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

这是一个live example .

关于c++ - 如何提取__VA_ARGS__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16372780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com