将原始数据类型传递到C 中的函数

passing primitive data type to a function in c++

本文关键字:函数 原始 数据类型      更新时间:2023-10-16

我想实现这样的函数

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

如何通过boolintdouble数据类型在C 中实现?

类型线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';
}

您也可以对第二种方法(读者的练习)进行示例。

如果您真的想这样做,则可以使用TypeID操作员通过类型。

例如。double d = string_to(" 1223.23",typeid(double));

使用库函数ATOI,STOD将更有意义。

如果您的目标是编写更多统一代码,则可以编写一个转换器对象并使用方法过载以按类型进行自动选择。

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

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

#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