Print the variable name in #define

I am trying to print the console using a macro, the variable name for the value of the display items during debugging (logging). How to do it? I tried the following, but it does not work.

#define MY_PRINT(x) std::cout << "'x'=" << x << std::endl; int main(){ int my_variable=3; MY_PRINT( my_variable ); // I would like to print to console // 'my_variable'=3 } 
+6
source share
2 answers

Auch ... I found a solution.

I have to write a macro like this

  #define MY_PRINT(x) std::cout << #x"=" << x << std::endl 
+17
source

For C ++, I use this:

 #define STR(x) #x << '=' << x int main() { int i = 1; std::string str("hello"); std::vector<std::string> vec; my_class mc; ... std::cout << STR(i) << std::endl << STR(str) << std::endl << STR(vec) << std::endl << STR(mc) << std::endl; return 0; } 

Thus, the compiler chooses a streaming operator based on the data type, so you do not need to worry about different macros for each, and it can go to any std :: ostream, not just std :: cout. Just provide the appropriate data streaming operator:

 std::ostream operator<<(std::ostream&, const T&); std::ostream operator<<(std::ostream&, const std::vector<T>&); etc 

But I would like for there to be a templated way to replace the macro, or at least the variable name provided by #x.

+2
source

Source: https://habr.com/ru/post/899289/


All Articles