传递任何类型的变量用于自定义的打印调试实现

huangapple go评论60阅读模式
英文:

Passing a variable of any type for a custom print-debugging implementation

问题

我正在为学校作业实现一个打印调试系统。如果答案很明显,我很抱歉,因为我仍在学习C++。

我想要创建一个函数,它接受三个参数:一个错误信息,一个变量名和变量本身,并将这些信息记录在某个地方,以便以后查看。它将工作如下:

int bad_variable = 2;
debug_log("Variable unexpected value", "bad_variable", bad_variable);

问题是,当将 bad_variable 传递给 debug_log 时,我不知道应该期望什么类型的变量,因此无法定义它。据我所知,没有办法解析未知类型的变量... 但是C++标准库在函数 std::to_string 中正是这样做的!

std::to_string 可能是解决我的问题的答案,我可以将 bad_variable 传递给 std::to_string 来将其转换为字符串,然后让 debug_log 期望输出字符串。但是,每次调用日志函数时都必须键入 std::to_string,对我来说似乎是一个拼凑的解决方案,而一定有更简单的答案。我希望保持这个调试函数尽可能简单。如何创建一个函数,它接受未知类型的变量,并生成包含该变量值的字符串?

英文:

I am implementing a print debugging system for a school assignment. I apologize if the answer is obvious, I am still learning c++.

I want to create a function, that takes three parameters: an error, a variable name, and the variable itself, and logs such information somewhere that can be viewed later. It would work like this:

int bad_variable = 2;
debug_log("Variable unexpected value", "bad_variable", bad_variable);

The problem is, I would have no idea what type of variable to expect when parsing bad_variable to debug_log, and therefore it cannot be defined. To my knowledge there is no way to parse a variable of an unknown type... however the c++ standard library does just that in the function std::to_string!

std::to_string could be the answer to my problem, I could just pass my bad_variable into std::to_string to convert it to a string, having debug_log expect the output string. However, I would have to type std::to_string every time I called the log function.

debug_log("Variable unexpected value", "bad_variable", std::to_string(bad_variable));

This to me seems like a patchwork solution to something that must have a simpler answer. I want to keep this debug function as simplistic as possible. How could I create a function that takes an unknown variable type, and generates a string containing the value of that variable?

答案1

得分: 1

如何创建一个函数,该函数接受未知变量类型,并生成包含该变量值的字符串?

由于您已经标记了这个问题为C++,一种不错的方法是使用模板:

template<typename T>
std::string convToString(T value) {
    std::ostringstream oss;
    oss << value;
    return oss.str();
}
英文:

> How could I create a function that takes an unknown variable type, and generates a string containing the value of that variable?

Since you've tagged this question C++, one nice way of doing so is by using templates:

     template&lt;typename t_value&gt;
      string convToString(t_value value)  {
       std::ostringstream oss; 
       oss &lt;&lt; value;  
       return oss.str();
     }

huangapple
  • 本文由 发表于 2020年1月4日 01:42:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定