如何自动打印输入的 C++ 函数参数值

tin*_*lyx 5 c++ gcc clang

我想知道是否有宏或标准方式(用于调试目的)来自动打印函数 f 的参数值,就像__FUNCTION__打印/显示函数签名一样?例如,

void foo(int x, string y) {
  cout << __FUNCTIION_ARGS__ << endl;
}
Run Code Online (Sandbox Code Playgroud)

应显示x, 和的值y

如果标准方式没有这种魔法,是否可以编写宏/模板来执行此操作?

- 更新 -

根据@jxh 的评论,如果使用宏/模板无法在所讨论的函数内打印,是否可以在调用方自动执行此操作,例如:

call(foo,x,y);
Run Code Online (Sandbox Code Playgroud)

它打印每个参数值,和行为相同与foo(x,y) 仿佛它是在每一个其他方面直接调用?如果一个值不可打印(例如指针、函数),包装器call只能打印一个不透明的值,例如<ptr><noprint>

谢谢

PS我正在使用gcc,(将来也会使用clang)。

Que*_*tin 5

我的看法:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出 :

Params : hello 3.14 42
hello 3.14 42
57
Run Code Online (Sandbox Code Playgroud)

可变参数模板很有趣!


pri*_*nce 1

没有用于打印参数的宏,但您可以使用__PRETTY_FUNCTION__宏打印函数原型