Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading with different return types

I know we are not allowed to overload functions based on return type only. Suppose I have two functions double convert(string num) and int convert(string num) Consider the following sample code :

double convert(string num){
    stringstream ss;
    double d_num;
    ss<<num;
    ss>>d_num;
    return d_num;
}

int convert(string num){
    int i_num;
    /*.....
   same as previous
   .....
   */
   return i_num;
}

And in the main() :

int main(){
    string st="09122321";
    double d1=convert(st);
    int i1=convert(st);

}

Although I overloaded the function differring only in return type but as I am assigning them to data types based on their return type wasn't I supposed to get the converted string num in double d1 and int i1 ?

Now I get the error similar to:

error: new declaration 'int convert(std::string)'| error: ambiguates old declaration 'double convert(std::string)'|

How will I make the convert() work if I want it to have it different return types by overloading the function ?

like image 778
Abrar Avatar asked Jun 16 '26 23:06

Abrar


1 Answers

How will I make the convert() work if I want it to have it different return types by overloading the function ?

You can create a simple function template.

template <typename T>
T convert(std::string const& num){
    std::istringstream ss(num);
    T d_num;
    ss>>d_num;
    return d_num;
}

and specialize it for std::string so that the input argument is used to copy construct the returned std::string.

template <>
std::string convert<std::string>(std::string const& in){
    return in;
}

and use it as:

auto d1 = convert<double>(st);
auto i1 = convert<int>(st);
like image 121
R Sahu Avatar answered Jun 19 '26 16:06

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!