0

I tried the following code for debugging in a C++17 template:

Basically I want to write a general debugging statement which would yield, say, int a=2; then deb(a) should output-> {a: 2} and for multivariables, it should be output: {a: 2,b: 3,...}

template<typename... Args>void deb(Args... args){
  (((cout<<#args)<<" "<<args),...);
  cout<<"\n";
}

And in my main function, I executed the following commands:

int a=2, b=3, c=4;
deb(a, b, c);

It shows a compilation error, stray # in program.

Where am I wrong?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 8
    Whats the `#` doing in there? – tkausl Sep 09 '21 at 18:36
  • 2
    What did you expect `#args` to do? – UnholySheep Sep 09 '21 at 18:36
  • 1
    Looks like you're trying to do a [fold expression](https://en.cppreference.com/w/cpp/language/fold) fortunately there are examples. The `#` isn't necessary and shouldn't be there. – Mgetz Sep 09 '21 at 18:37
  • 2
    `#` only works in this manner inside of macros (`#define`s). – HolyBlackCat Sep 09 '21 at 18:37
  • The `#` operator is only legal in a macro and is evaluated before compilation even starts. Not what you seem to want – IWonderWhatThisAPIDoes Sep 09 '21 at 18:38
  • Also, even before C++17, I am sure there are many examples showing how to do a "typesafe printf" using variable templates. I don't see the need to try and invent your own syntax, especially when there are many examples that can be found online. – PaulMcKenzie Sep 09 '21 at 18:41
  • maybe you meant to put #args in double quotes as a string literal `"#args"`? – franji1 Sep 09 '21 at 18:41
  • I believe that processing multiple arguments in one macro is complicating the issue. Stay with a macro that displays one variable. Call multiple times, once per variable, as necessary. – Thomas Matthews Sep 09 '21 at 18:45
  • 1
    Self-promoting solution to print the variables names and their values: [how to print many variables with there name and their corresponding value in c++?](https://stackoverflow.com/a/64215959/7582247) – Ted Lyngmo Sep 09 '21 at 18:45
  • Then how can I get the required output? Can anyone please provide a working example. – Mukul Kadyan Sep 09 '21 at 18:48
  • 1
    @MukulKadyan Did you see the solution I linked to? If I understand you correctly, it does exactly what you want. – Ted Lyngmo Sep 09 '21 at 18:50
  • @MukulKadyan *Can anyone please provide a working example* -- To reiterate, what you should have done is research to see if this problem, even it doesn't fit exactly with what you want outputted, has already been solved. Outputting a list of parameter names and values is one such problem that has been solved many times. Thus what you should have done is taken one of those solutions and attempt to retrofit it to your requirements. – PaulMcKenzie Sep 09 '21 at 18:58

0 Answers0