Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print input c++ function parameter values automatically

Tags:

c++

gcc

clang

I was wondering if there is a macro or standard way (for debugging purposes) to automatically print the value of the parameters of a function f, just like __FUNCTION__ prints/shows the function signature? For example,

void foo(int x, string y) {
  cout << __FUNCTIION_ARGS__ << endl;
}

should show the values of x, and y.

If there is no such magic the standard way, is it possible to write a macro/template to do this?

--Update--

Per @jxh's comment, if print inside the function in question is impossible with macro/templates, is it possible to do it automatically on the caller-side, with something like:

call(foo,x,y);

which prints every parameter value, and behaves the same with foo(x,y) as if it is called directly in every other aspect? If a value is not printable (e.g. pointers, functions), the wrapper call can just print an opaque value such as <ptr> or <noprint>.

Thanks

P.S. I am using gcc, (and also clang in the future).

like image 790
thor Avatar asked Sep 30 '22 06:09

thor


1 Answers

My take on it :

#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;
}

Output :

Params : hello 3.14 42
hello 3.14 42
57

Variadic templates are fun !

like image 142
Quentin Avatar answered Oct 19 '22 02:10

Quentin