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

标签 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;
}
我得到了类似 [args]:1[args]:3 的输出
但我想要像 [a]:1[b]:3 这样的输出

最佳答案

一种方法是使用 #__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::ostringstream 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::ostringstream 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 double bar = 2;
    const std::string Hello = "world";

    debug(foo,bar,Hello);
}
可能的输出:
example.cpp(49) main: foo=1 bar=2 Hello=world
Demo

关于c++ - c++ - 如何在c++中打印许多具有名称及其对应值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64213475/

相关文章:

c++ - 在笛卡尔平面上给定N条线。如何有效地找到最底线的交点?

c++ - 我必须从5的数组中找到4个数字的最大和。我的代码对于更大的数字失败

c++ - 如何避免变量的 __attribute__((weak)) 多重定义错误? [cl2.hpp]

c++ - 编译时如何使用外部模板参数

c++ - 模板类中的模板方法特化

c++ - 制作打印所有变量名称和值的可变参数宏/方法

c++ - 将 OSG 的 osgViewerQt 示例与 Qt 信号/槽一起使用

c++ - 声明模板类的模板友元函数

c++ - 标签调度、可变参数模板、通用引用和遗漏的 const 说明符

c++ - 在不使用 boost::any 的情况下将参数存储在可变参数模板函数中