How to extract __VA_ARGS__?(如何提取 __VA_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__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何提取 __VA_ARGS__?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
