c++ - 如何在c ++中打印许多带有名称及其对应值的变量?

Ayu*_*rma 3 c++ templates variadic-templates

#include <bits/stdc++.h>
using namespace std;

#define __deb(X...) (cout << "[" << #X << "]:" << X)
template <typename... type>
void debug(type &&... args)
{
    ((__deb(args)), ...);
}

int main()
{
    int a = 1, b = 3;
    debug(a,b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到了像 [args]:1[args]:3 这样的输出,但我想要像 [a]:1[b]:3 这样的输出

Ted*_*gmo 5

一种方法是#__VA_ARGS__在 C++ 函数中使用和解析该字符串来引用所有宏参数。

例子:

#include <iostream>
#include <sstream>
#include <string>
#include <utility>

template<typename T, typename... Args>
std::string debug_detail(const char* names, T&& var, Args&&... args) {
    std::stringstream builder;

    // find variable end
    const char* end = names;
    while(*end != ',' && *end != '\0') ++end;

    // display one variable
    (builder << ' ').write(names, end - names) << '=' << var;

    // continue parsing?
    if constexpr(sizeof...(Args) > 0) {
        // recursively call debug_detail() with the new beginning for names
        builder << debug_detail(end + 1, std::forward<Args>(args)...);
    }

    return builder.str();
}

template<typename... Args>
void debug_entry(const char* file, int line, const char* func,
                 const char* names, Args&&... args) {
    std::stringstream retval;

    // common debug info
    retval << file << '(' << line << ") " << func << ':';

    // add variable info
    retval << debug_detail(names, std::forward<Args>(args)...) << '\n';

    std::cout << retval.str();
}

// the actual debug macro
#define debug(...) \
    debug_entry(__FILE__,__LINE__,__func__,#__VA_ARGS__,__VA_ARGS__)

int main() {
    int foo = 1;
    const int bar = 2;
    const std::string& Hello = "world";
    debug(foo,bar,Hello);
}
Run Code Online (Sandbox Code Playgroud)

可能的输出:

./example.cpp(48) main: foo=1 bar=2 Hello=world
Run Code Online (Sandbox Code Playgroud)

演示