[英]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. 如果您的类的构造函数使用const char *,则可以使用伪造的构造函数宏将变量名传递给实际的构造函数。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.