I will like to be able to do something like this
int myVar = 3;
void logger(int param) {
std::cout << nameOf(param) << ": " << param << std::endl;
}
logger(myVar); // prints "myVar: 3"
I will like to be able to do something like this
int myVar = 3;
void logger(int param) {
std::cout << nameOf(param) << ": " << param << std::endl;
}
logger(myVar); // prints "myVar: 3"
No, you can't do this in the C++ language yet, since there is no reflection facility to do this.
However, you can use preprocessor macros to achieve the effect you want. Note that macros are dangerous, and should be avoided as far as possible.
First, write an implementation function that takes the parameter value, and the parameter name, like this:
void logger_impl(int param, std::string param_name) {
std::cout << param_name << ": " << param << std::endl;
}
Then you can write a macro that generates a string from the variable name in the call site, using #
(the stringification operator), and then uses that string in the call to the implementation function:
#define logger(p) logger_impl(p, #p)
Here's a demo.
Yes, it is possible!
Look at the following example:
#include <string>
// add the following macro
#define NAMEOF(x) #x
int main(){
int myvar{ 5 };
std::cout << NAMEOF(myvar) << "=" << myvar << std::endl; // myvar=5
// it could also be stored in a variable
std::string myvarname{ NAMEOF(myvar) };
return 0;
}