简体   繁体   English

如何根据内部代码更改返回类型? (字符串到数字的转换)

[英]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.). 问题在于它需要两个参数,第二个参数提供了有关我要返回的数字类型(int或float等)的线索。

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)? 它返回一个十进制数据类型(例如float),否则返回整个数据类型(例如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 : 我认为您想要它,只是在调用string_to_num之前摆脱指示类型:

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

But, you already are indicating the type by <double> . 但是,您已经通过<double>指示了类型。 A simple syntax sugar, auto is what you want. 一个简单的语法糖, auto是您想要的。 (It's compile time) (现在是编译时间)

Otherwise, you need a variant type, and it's far from your string_to_num definition. 否则,您需要一个变体类型,并且它与您的string_to_num定义string_to_num It has a lot of overhead. 它有很多开销。

You're code is already OK, and the output is based on T . 您的代码已经确定,并且输出基于T So, in real programs you have no problem. 因此,在实际程序中,您没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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