c++ - 如何在c ++中打印许多带有名称及其对应值的变量? [英] how to print many variables with there name and their corresponding value in c++?
本文介绍了c++ - 如何在c ++中打印许多带有名称及其对应值的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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
I got output like [args]:1[args]:3 but I wanted output like [a]:1[b]:3
推荐答案
一种方法是使用 #__VA_ARGS__
引用所有宏参数并在 C++ 函数中解析该字符串.
One way could be to quote all the macro arguments using #__VA_ARGS__
and parse that string in the C++ function.
示例:
#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
这篇关于c++ - 如何在c ++中打印许多带有名称及其对应值的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文