使用 C++ 宏从嵌套括号中提取项目

Using a C++ macro to pull out items from nested parentheses

在 C++ 中,使用宏很容易将参数分开执行以下操作:

#define printThings(stringPrinting, param1, param2) printf(stringPrinting, param1, param2)

printThings(stringPrinting, param1, param2)

// Goes to

printf(stringPrinting, param1, param2)

但是我找不到这样做的方法:

#define printThings(a, b) printf(?)

printThings(stringPrinting, Blarg(param1, param2))

// Goes to

printf(stringPrinting, param1, param2)

这可能吗?

你可以

#define UNPACK( a, b ) a, b
#define printThings( s, args ) printf( s, UNPACK args )

这是高级预处理器内容的主要宏习语之一。处理可变参数的规范技术,例如在参数上分发一些宏调用,是某个我不记得的人(法语?)在 1999 年的 comp.lang.c 或 comp.std.c 新闻组中发布的,我认为是,也许是以后。 Boost 预处理器库和 Boost 参数库有很多非常高级的东西。如果你想学习。 :)


注意 1:看起来您真的想要一个可变参数宏,用 ...(三个点)而不是命名参数定义。我相信你可以 google。


注意 2:由于宏是 Evil™,您可能真的想要

的一些变体
template< class... Args >
void printThings( char const* s, Args&&... args )
{
    printf( s, std::forward<Args>( args )... );
}

免责声明:未经测试的代码。