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:
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....
Yes, you can define a generic method in a non-generic class in Java.
To construct an instance of a generic type GetType(String) method overload with a string describing the type, and by calling the GetGenericTypeDefinition method on the constructed type Dictionary\<String, Example> ( Dictionary(Of String, Example) in Visual Basic).
A generic class can be a base class to other generic or non-generic classes or abstract classes. A generic class can be derived from other generic or non-generic interfaces, classes, or abstract classes.
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.
Since C++11 you can do it with variadic template and perfect forward. E.g. write a template function, which perfect forwards its parameters to the constructor of the object with type specified by template parameter.
template <typename T, typename... Ts>
T* MyAwesomeFunc(Ts&&... params){
return new T(std::forward<Ts>(params)...);
}
Then use it as
Foo* foo = MyAwesomeFunc<Foo>();
Bar* bar = MyAwesomeFunc<Bar>(2,3,5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With