如何自动打印输入的c++函数参数值
How to print input c++ function parameter values automatically
我想知道是否有一个宏或标准的方式(用于调试目的)自动打印函数f的参数值,就像__FUNCTION__
打印/显示函数签名一样?例如,
void foo(int x, string y) {
cout << __FUNCTIION_ARGS__ << endl;
}
应显示x
和y
的值。
如果没有这种神奇的标准方式,是否有可能编写一个宏/模板来做到这一点?
——更新
根据@jxh的评论,如果在有问题的函数内部打印是不可能的宏/模板,是否有可能在调用方自动完成,如:
call(foo,x,y);
打印每个参数值,并且与foo(x,y)
的行为相同,好像在其他方面直接调用?如果一个值是不可打印的(例如指针,函数),包装器call
可以打印一个不透明的值,如<ptr>
或<noprint>
。
注:我正在使用gcc,(将来还会使用clang)。
我的看法:
#include <iostream>
// Dummy parameter-pack expander
template <class T>
void expand(std::initializer_list<T>) {}
// Fun
template <class Fun, class... Args>
typename std::result_of<Fun&&(Args&&...)>::type
call(Fun&& f, Args&&... args) {
// Print all parameters
std::cout << "Params : ";
expand({(std::cout << args << ' ', 0)...});
std::cout << 'n';
// Forward the call
return std::forward<Fun>(f)(std::forward<Args>(args)...);
}
// Random test function
int myFunc(std::string const &s, double d, int i) {
std::cout << s << ' ' << d << ' ' << i << 'n';
return 57;
}
int main()
{
// Painless call
std::cout << call(myFunc, "hello", 3.14, 42) << 'n';
return 0;
}
输出:Params : hello 3.14 42
hello 3.14 42
57
可变模板很有趣!
没有用于打印参数的宏,但是您可以使用__PRETTY_FUNCTION__
宏
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数