user3566905
user3566905

Reputation: 113

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?

Upvotes: 7

Views: 10373

Answers (1)

max66
max66

Reputation: 66190

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.

Upvotes: 9

Related Questions