0

Is there any way, using c++11, to get the name of a variable that is a (possibly static) constexpr.

For example:

struct Foo{
    int x, y, z;
};

constexpr Foo PrintMe = { 1, 2, 3};

I would like to get a string "PrintMe" somehow.

I know that I can use a macro like:

#define NAME_OF( v ) #v

and call

std::cout << NAME_OF(PrintMe) << std::endl;

which will print

PrintMe

Is there a way to get the following print the same?

Foo a = PrintMe;

std::cout << Magic(a) << std::endl;

EDIT: I am not looking for some magic solution which will make the call to Magic(a) work. I understand that doing something to accommodate what I want will require defining some macros or templates. Like enums can be printed in some sort of way (How to convert an enum type variable to a string?

Community
  • 1
  • 1
ZivS
  • 2,094
  • 2
  • 27
  • 48

2 Answers2

2

If you want to do this without macro, there is no way, no. You would have to do some kind of meta class in order to achieve this.

Telokis
  • 3,399
  • 14
  • 36
  • It doesn't exist yet, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0194r3.html for a proposal. Until then you need something outside the language that processes your source to generate extra information (such as Qt's `moc`) – Jonathan Wakely Feb 14 '17 at 16:15
0

Foo a = PrintMe; has value semantics, it assigns the value of PrintMe to a. Afterwards, there is no way of checking whether this value came from PrintMe. Of course, you can check for the same value:

std::string Magic(const Foo& a) {
    if (a == PrintMe) { return NAME_OF(PrintMe); };
    else { /* whatever you want to happen here */ }
}

But this will of course also return "PrintMe" if you did

Foo a = {1, 2, 3};

Because the value is the same as PrintMe.

flyx
  • 35,506
  • 7
  • 89
  • 126