简体   繁体   中英

How to print name of object that is using constructor

I am looking for a way to print the name of the variable on which an instance's constructor is being invoked, from inside the constructor:

#include <iostream>

struct A {
    A() {
       std::cout << "variable name = " /*magic here*/ << "\n";
    }
};

int main() {
    A abc;  // should output "variable name = abc"
    A def;  // should output "variable name = def"
}

Is this possible and how?

I don't think there's any way to do that without using macros.

If your class had a constructor taking a const char* then you could use a fake constructor macro to pass the variable name into the real constructor. I'm not sure why you'd want to do that though and this is a pretty ugly solution.

#define CONSTRUCT(type, name) type name(#name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM