Search code examples
c++variadicvariadic-macros

macro that defines entire derived class from one function and certain type specifiers?


I have a class called system. A system takes some object managers and changes all objects in them in some way.

For example there might be a system that draws all images in a imageManager.

Every derived class works somewhat like this (pseudo code):

class someChildClass : public System{
private:
     someObjectManager &mang1; //these are used by the update method.
     someOtherObjectManager &mang2;//the update method changes these somehow
public:
     someChildClass(someObjectManager &mang1, someObjectManager &mang2)
     :mang1(mang1),mang2(mang2){
     }
     virtual void update(){
     //this is pure virtual in the System base class.
     //Do something with the managers here
     }
}

I feel like writing everything but the update method is a waste of time and a source of errors. I wanted to write a macro that basically makes a class like this like so:

QUICKSYSTEM(thisIsTheSystemName, someObjectManager, mang1, someOtherObjectManager, mang2, ... (infinite possible Managers. So a variadic macro?)){
//this is the update function
}
}//this is the end braked for the class declaration. Its ugly but I dont know how I could do the function differently? 

well I am having some problems making the macro. Everything works fine until I need to split the variadic arguments into the names and the types. I dont know if this is even possible now, since I cant go back and forth in the arguments easily or apply a easy step to them to make sure that every 2nd is the name of the variable. I would be ok with omitting the possibility for names and just had the types with some sort of automatic naming (manager1,manager2,manager3 or something like that).

If this isnt possible using a macro, what would be a better way to avoid mistakes and cut some time in the constructor and class declaration part?


Solution

  • Yeah, macros are really, really not the way to do this. C++ has templates, which follow C++ syntax and support C++ expressions. Macros instead use their own preprocessor language, which is almost entirely unaware of C++.

    You'll want to read up a bit on std::tuple as well. It's going to be rather tricky to handle all those managers with those names. Tuples are the Standard solution for that. managers.get<0> and managers.get<someObjectManager> both work.