通用地打印一系列变量及其名称

Generically print a sequence of variables with their names

本文关键字:变量 一系列 打印      更新时间:2023-10-16

我想:

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)...)才能实现与第一个场景类似的功能,但如果我可以只使用逗号会更好。其中一个问题的解决方案可能很容易适用于同时解决这两个问题。

您可以使用BOOST_PP_TUPLE_TO_SEQ将其转换为序列,如下所示:

#define PRINT_ARGS(...) PRINT(BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))

这是我的解决方案。不是很动态,你必须事先知道你会有多少争论:

// 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