I'm designing a class where there's a method that should return a different data type depending on certain circunstances.

Specifically, I'm reading from a text file. If the data found are strings of characters, I'd like to return a vector of strings. On the other hand, I'd like to return a vector of floats if the data are numbers.

template <typename T>

vector<T> funcion(string typeConversion){

if (typeConversion== 'String')
//...
return list<string>
else if (typeConversion == 'Number')
//...
return vector<float>

}

I don't think this is possible with C++ (in Python, for instance, I think that methods can return every data type).

Do you know any alternative to solve my problem?

Thanks!

Recommended Answers

All 2 Replies

MS-Windows COM programming uses a structure called a VARIANT that might be usefule to you. It has two members: a union of different data types, and an integer that indicates the kind of data was put in the union. It would look like this:

struct data
{
     int type;
     union
     {
          std::string str;
          float fl;
     };
};

With that you could have your function return any kind of data you want. I would recommend the function is passed the vector by reference to avoid all the complications of duplication that exists when its used as the return value.

bool foo( vector<struct data>& aList, string typeConversion )
{
   // fill in the vector
   // then return either true or false
   // depending on success or failure of this function
   return true;
};

int main()
{
    vector<struct data> aList;
    foo(aList, "123 456");
}

You are correct that in standard c++ you cannot overload a function by return type alone.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.