将原始数据类型传递给c ++中的函数

时间:2015-05-01 06:15:46

标签: c++

我想实现像这样的函数

double d = string_to("1223.23",double);
int i = string_to("1223",int);
bool d = string_to("1",bool);

如何传递boolintdouble数据类型以在c ++中实现此功能?

3 个答案:

答案 0 :(得分:9)

类型行intdoublebool只能作为template参数传递。

您可以使用以下模板:

#include <string>
#include <sstream>
#include <iostream>

template<typename DataType>
DataType string_to(const std::string& s)
{
    DataType d;
    std::istringstream(s) >> d; // convert string to DataType
    return d;
}

int main()
{
    double d = string_to<double>("1223.23");
    int i = string_to<int>("1223");
    bool b = string_to<bool>("1");

    std::cout << "d: " << d << '\n';
    std::cout << "i: " << i << '\n';
    std::cout << "b: " << b << '\n';
}

作为替代方案,您可以通过引用传递数值类型并依赖函数重载来选择正确的函数:

void string_to(const std::string& s, double& d)
{
    d = std::stod(s);
}

void string_to(const std::string& s, int& i)
{
    i = std::stoi(s);
}

void string_to(const std::string& s, bool& b)
{
    std::istringstream(s) >> std::boolalpha >> b;
}

int main()
{
    double d;
    int i;
    bool b;

    string_to("1223.23", d);
    string_to("1223", i);
    string_to("true", b);

    std::cout << "d: " << d << '\n';
    std::cout << "i: " << i << '\n';
    std::cout << "b: " << b << '\n';
}

你也可以模仿第二种方法(读者的练习)。

答案 1 :(得分:3)

如果您确实想这样做,可以使用typeid运算符传递类型。

E.g。 double d = string_to(&#34; 1223.23&#34;,typeid(double));

使用atoi的库函数,stod会更有意义。

如果您的目标是编写更统一的代码,那么您可以编写一个Converter对象并使用方法重载来按类型自动选择。

class Converter 
{
public:
    void fromString(double& value, const char* string);
    void fromString(int& value, const char* string);
    void fromString(long& value, const char* string);
};

答案 2 :(得分:0)

这是使用标签分派的另一种方式。您可以编译并运行此示例。

#include <iostream>
#include <string>
#include <cmath>


namespace detail {

    // declare the concept of conversion from a string to something

    template<class To>
    To string_to(const std::string&);

    // make some models of the concept

    template<>
    int string_to<int>(const std::string& s) {
        return atoi(s.c_str());
    }

    template<>
    double string_to<double>(const std::string& s) {
        return atof(s.c_str());
    }

    template<>
    std::string string_to<std::string>(const std::string& s) {
        return s;
    }

    // ... add more models here

}

// define the general case of conversion from string with a model tag
// note the unused parameter allows provision of a model that is never used
// thus the model will in all likelihood be optimised away
template<class To>
To string_to(const std::string& from, const To& /* model_tag is unused */)
{
    // dispatch to correct conversion function using the To type
    // as a dispatch tag type
    return detail::string_to<To>(from);
}

using namespace std;


int main()
{
    // examples
    int a = string_to("100", a);
    double b = string_to("99.9", b);
    const string s = string_to("Hello", s);

    cout << s << " " << a << " " << b << endl;

   return 0;
}

输出:

Hello 100 99.9