user3566905
user3566905

Reputation: 113

C++ static non-member function returning object of a template class

I have a static non-member function which returns a template class object depending on the type of the object.

template< typename T >
class Example
{
.... 
};

static Example non_member_function(int var) {
  if (var == 1)
     return Example<float>;
  else
     return Example<int>
}

This is not working as return type Example is a template. How can I write this return type

Upvotes: 0

Views: 1099

Answers (3)

Aganju
Aganju

Reputation: 6395

You cannot use different types in the return value without making the function a template too - each return type defines a new function, they are all different.

The better approach is to return a pointer, which does allow polymorphism.

Note though that you are then returning a pointer to a local object, which is undefined after the function ends. You would need to return a new object (return new Example<float>;), or make the two objects static inside the function and return their addresses -depending if you want to return each time a new object, or always the same one.

Upvotes: 1

aschepler
aschepler

Reputation: 72311

C++ does not (directly) allow what you're trying to do. Example<float> and Example<int> are unrelated classes that do not necessarily have anything at all in common. So you can't have a single function return two different things, any more than you could write a function that sometimes returns a double and sometimes returns a std::vector<int>.

There are some ways to do similar things, but which is appropriate really depends on why you want the function to act this way and what you intend to do with the returned values.

Upvotes: 0

Steve
Steve

Reputation: 1757

It doesn't really work like that - the compiler needs to know what the return type is, and you're returning either Example <int> or Example <float> (which are different types) depending on a variable passed in at runtime.

If you know what type you want at compile time, you can do this:

template <typename T> static Example<T> non_member_function() {
     return Example<T> ();
}

And then call it like this:

Example <int> example1 = non_member_function <int> ();

or

Example <float> example2 = non_member_function <float> ();

Upvotes: 0

Related Questions