我正在寻找一种允许记录函数输入参数的功能。例如:
void func(std::string& input_name, const int n){
// print current function's inputs' type, name, and value
}
调用该函数后,以下内容将作为字符串打印或可读,
input1:
type: std::string,
name: input_name,
value: "something",
input2:
type: int,
name: n,
value: 12,
有人对这样的目标有建议吗
- - - - - - 编辑
如果无法打印类型或名称,对我来说也可以。
我对接近此的解决方案很灵活,例如我们是否可以获得输入参数列表等。
打印变量的类型和值相当简单。但是变量名称在运行时并不存在,因此获取变量名称作为字符串而不对其进行硬编码的唯一方法是在编译时使用宏。宏具有对标记进行字符串化的功能。
尝试这样的事情(抱歉,这是凭记忆,我现在无法使用编译器,我将在今天晚些时候更新):
#include <iomanip>
#include <typeinfo>
#include <type_traits>
template <typename T>
std::string getTypeName()
{
// TODO: to get a more human-readable output, use
// if-constexpr, or template specialization, or one
// of the solutions from https://stackoverflow.com/q/281818/65863...
return typeid(T).name();
}
template<typename T>
std::string stringify(const T& param)
{
std::ostringstream oss;
if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, char*> || std::is_same_v<T, const char*>)
oss << std::quoted(param);
else
oss << param;
return oss.str();
}
template <typename T>
void doLog(int num, std::string_view name, const T& value)
{
std::cout << "input" << num << ":" << std::endl
<< "\ttype: " << getTypeName<T>() << "," << std::endl
<< "\tname: " << #param << "," << std::endl
<< "\tvalue: " << stringify(param) << "," << std::endl;
}
#define LOG(num, param) doLog(num, #param, param)
void func(std::string& input_name, const int n){
LOG(1, input_name)
LOG(2, n)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)