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__?
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
