我想:
int a = 2;
int b = 3;
// ...
PRINT1(a, b, ...);
PRINT2(a, b, ...);
PRINT1
应扩展为:
std::cout << "a = " << a << ", b = " << b << ... << std::endl;
// note: in "a = ...", "a" is the name of the variable, i.e.:
// PRINT(bar, ...) should print "bar = ..."
和PRINT2
应扩展为(使用cppformat):
fmt::print("a = {}, b = {}, ...", a, b, ...);
现在我正在使用Boost.PP并且必须编写PRINT((a)(b)(c)...)
来实现与第一个场景类似的东西,但如果我可以使用逗号代替它会更好。其中一个问题的解决方案很可能很容易适应两者。
答案 0 :(得分:1)
您可以使用BOOST_PP_TUPLE_TO_SEQ
将其转换为序列,如下所示:
#define PRINT_ARGS(...) PRINT(BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))
答案 1 :(得分:0)
这是我的解决方案。不是很有活力,你必须事先知道你将有多少参数:
// Using macros:
#define PRINT1_1(A) std::cout << "a = " << A << std::endl;
#define PRINT1_2(A,B) std::cout << "a = " << A << ", b = " << B << std::endl;
#define PRINT2_1(A) fmt::print("a = {}", A);
#define PRINT2_2(A,B) fmt::print("a = {}, b = {}", A, B);
// Using `va_arg`:
#include <iostream>
#include <cstdarg>
void PRINT1(int argc, ...)
{
va_list args;
va_start(args, argc);
char vc = 'a';
int val = argc;
for (int i = 0; i < argc; ++i, ++vc) {
std::cout << vc << " = " << va_arg(args, int);
if (i < argc - 1)
std::cout << ", ";
}
va_end(args);
std::cout << std::endl;
}
// similarly implement PRINT2
int main()
{
PRINT1_2(1,2);
// first argument specifies the number
// of the remaining arguments:
PRINT1(3, 1,2,4);
return 0;
}
输出:
a = 1, b = 2
a = 1, b = 2, c = 4