Normally, if I have a Foo
, or a Bar
, I would do something like:
Foo* foo = new Foo();
Bar* bar = new Bar(2,3,5);
Is there a way using templates or macros, that I can construct a function, such that I can do something like:
Foo* foo = MyAwesomeFunc(Foo);
Bar* bar = MyAwesomeFunc(Bar,2,3,5);
The actual method signature of
MyAwesomeFunc
is not important to me.
Foo
and Bar
need not be related in any possible way, and may have completely different constructors. Additionally, I may want to support any number of classes in the future without having to actually modify the code of MyAwesomeFunc
Is this possible ? A simple way would be to have both Foo
and Bar
inherit from some type, say Baz
, and have overloaded methods return a Baz
, which you cast back to Foo
or Bar
...
Baz* MyAwesomeFunc(){
return new Foo();
}
Baz* MyAwesomeFunc(int a,int b,int c){
return new Bar(a,b,c);
}
But the problems here is you would have to write:
- a method for each class supported
- and for each kind of constructor signature.
The goal, is to write a single class, method, or macro, where we can call one function (and pass it any arguments), but call the right constructor of the passed in object. Is this possible ?
The purpose of this question is to simply explore if it is possible to do something like this in C++. Please do not bring up shared pointers, unique pointers, the pitfalls of using new, as that is off topic.
EDIT: I would like to use only the STL, and avoid using things like Boost....