Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function return type as template

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?

like image 239
user3566905 Avatar asked Oct 25 '17 12:10

user3566905


1 Answers

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.

like image 192
max66 Avatar answered Oct 17 '22 02:10

max66