Home Using a template function with different returns for different types doesn't work
Reply: 0

Using a template function with different returns for different types doesn't work

user1395
1#
user1395 Published in July 17, 2018, 7:46 am

so I wrote something like that:

class MyClass
{
    enum varType {INTEGER, DOUBLE, VECTOR};

    int beautiful_integer;
    double awesome_double;
    std::vector<float> many_floats;

    template <class T>
      T getVariable(varType type)
      {
          if(type == INTEGER)
          {
             return beatiful_integer;
          }
          if(type == DOUBLE)
          {
             return awesome_double;
          }
          if(type == VECTOR)
          {
             return many_floats;
          }
      }

...

};

But my compiler throws error "In instantiation of ..." and basically tells me that the return types don't match (and lists all of the unmatched ones, except the right one) and then tries to instantiate it with another type (for example double) and tells me that the return type doesn't match with int and vector of floats.

What am I doing wrong and how to properly write a template function in order to return different types depeneding on the parameter it was called with. For example when I call:

MyClass some_class(); //EDIT: this should be MyClass some_class; 
                      //thanks for pointing it out
int some_number = some_class.getVariable(INTEGER);

I want to assign the value of beautiful_integer to some_number

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.506575 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO