简体   繁体   中英

How to change return type based on inner code? (string to number conversion)

For example, I have this code which converts from string to number:

#include <sstream>

template <typename T>
T string_to_num( const string &Text, T defValue = T() )
{
    stringstream ss;
    for ( string::const_iterator i=Text.begin(); i!=Text.end(); ++i )
        if ( isdigit(*i) || *i=='e' || *i=='-' || *i=='+' || *i=='.' )
            ss << *i;
    T result;
    return ss >> result ? result : defValue;
}

Problem is it requires two arguments, the second which gives it a clue as to what type of number I am returning (an int or a float etc.).

How can I make it so that if the string contains a decimal '.' it returns a decimal datatype (eg. float), otherwise an whole datatype (eg. int)?

Unless someone has a better code they can share to do this..?

The question is why you need this. I think you want it, just to get rid of indicating the type before calling string_to_num :

????? number = string_to_num<double>("123.21");
^^^^^
do_something(number);

But, you already are indicating the type by <double> . A simple syntax sugar, auto is what you want. (It's compile time)

Otherwise, you need a variant type, and it's far from your string_to_num definition. It has a lot of overhead.

You're code is already OK, and the output is based on T . So, in real programs you have no problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM