在C++中将基本数据类型作为参数传递给函数

3
我想实现这样的一个函数:
double d = string_to("1223.23",double);
int i = string_to("1223",int);
bool d = string_to("1",bool);

我该如何在C++中传递bool、int和double数据类型来实现这个功能?
3个回答

9

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

您可以这样使用模板:

#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';
}

你还可以将第二种方法进行模板化(这是给读者的练习)。


4

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

例如:double d = string_to("1223.23", 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);
};

1
这里还有另一种使用标签派发的方式。您可以编译并运行此示例。
#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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接