Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write a Class that will "Know" its own variable name

Tags:

c++

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?

like image 605
Xirema Avatar asked Dec 19 '22 21:12

Xirema


1 Answers

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.

like image 189
Mark B Avatar answered Dec 24 '22 03:12

Mark B