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?

10
  • 4
    What you are looking for is called reflection and it is not part of C++. Commented Feb 14, 2017 at 16:00
  • No. BTW what it has anything to do with constexpr. It is not possible in C++, irrespective of whether it is constexpr or not. Commented Feb 14, 2017 at 16:01
  • Also your title is misleading. You have a way to print a compile time variable, you are looking to print a run time variable. Commented Feb 14, 2017 at 16:01
  • Why do think you want this? Commented Feb 14, 2017 at 16:02
  • The same could be said on any "How to print the name of an enum" but there are way of creating those enums in such a way that their names could be printed Commented Feb 14, 2017 at 16:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't exist yet, see 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)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.