So let's suppose I have the following class definition:
class my_named_int {
public:
int value;
const string name;
my_named_int(int _value, /*...Does Something Go Here...?*/);
};
What I would like, is if I write the following code:
int main() {
my_named_int my_name(5);
std::cout << my_name.name << ":" << my_name.value << std::endl;
}
I would like the output to be:
my_name:5
Obviously, the easiest way to resolve this would be to write code that looks like this:
class my_named_int {
public:
int value;
const string name;
my_named_int(int _value, const string & _name);
};
int main() {
my_named_int my_name(5, "my_name");
std::cout << my_name.name << ":" << my_name.value << std::endl;
}
But of course, this adds repetitiveness to my code. Is there a way to do this in C++ without the "double-writing" of the variable name, and if so, how would I go about it?
In C++ variables do not know their own name.
The best you can do is use the preprocessor:
#define DECLARE_NAMED_INT(value, name) my_named_int name((value), #name);
That said this is not idiomatic C++ so you might consider looking at the real problem you're trying to solve and ask that as another question. Specifically I mean that reflection (Which seems to be what this question is about) is not a C++ feature and as such problems are typically solved in alternate ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With