Aryan Firouzian
Aryan Firouzian

Reputation: 2016

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

Let's say

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

So when the object is created:

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

In my case as the object names are pretty long, I am looking for macro to simplify that code to:

CreateA(objectNumber325);

There is some discussion how to pass variable name to a function here. But that is not quite the same thing, as I want to create the object and pass its name to constructor.

Upvotes: 0

Views: 483

Answers (1)

rustyhu
rustyhu

Reputation: 2147

#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;
}

Upvotes: 1

Related Questions