I want to write a function to return different class objects depending on the value of a parameter. Returning class objects are templated. I give the class name as a template argument to the function,
template< class T >
static T FindClassObjects(int var){
if(var==1)
return T<float>(var);
else
return T<int>(var);
Can I do this?
I want to write a function to return different class objects depending on the value of a parameter. [...] Can I do this?
Short answer: no.
Long answer.
The C/C++ languages are strongly typed; every single function return a type that must be known at compile type.
So it's impossible to have a function that return a type that depend from a value known at runtime.
It's different if you known the value var
at compile time: in this case you can develop different functions that return different types and compile time select which function to call depending to the var
value.
Anyway, you can go round this limit in different ways.
If you can use C++17, you can return a std::any
, that can contain any type; or (better, I suppose) a std::variant
, that can contain a value in a prefixed list of types.
Otherwise, if the different typed have a common base class, you (by example) can return a pointer to a base class.
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