使用 C++ 宏实例化一个对象并将其名称传递给构造函数

Instantiate an object and pass its name to constructor using c++ macro

假设

class A {
   A(string name) {
       //....
   }
}

所以创建对象时:

A* objectNumber324 = new A("objectNumber324");
A* objectNumber325 = new A("objectNumber325");

在我的例子中,由于对象名称很长,我正在寻找宏来将代码简化为:

CreateA(objectNumber325);

有人讨论如何将变量名传递给函数 here。但这并不完全相同,因为我想创建对象并将其名称传递给构造函数。

#include <string>
#include <iostream>

#define CreateA(name) \
        A* name = new A(#name)

// With type
#define CREATE_WITH_TYPE(type, name) \
        type* name = new type(#name)

// With name decoration
#define CREATE_WITH_DECO(type, name) \
        type* my_##name = new type(#name)

class A {
public:
   A(std::string name){
       std::cout << name << " created.\n";
   }
};

int main() {
    // example
    CreateA(objectNumber325);
    CREATE_WITH_TYPE(A, objectNumber324);
    CREATE_WITH_DECO(std::string, a_string);
    delete objectNumber324;
    delete objectNumber325;
    delete my_a_string;
}