如何将std::string转换为构造函数中几种类型中的任何一种

How to convert std::string to any of several types in constructor?

本文关键字:任何一 几种 类型 构造函数 std string 转换      更新时间:2023-10-16

我有下面的类模板,它有一个成员变量,其类型由模板参数决定。我想在构造函数中初始化这个成员的值,它只接受一个std::string。因此,我的问题是我需要将std::string转换为几种类型中的任何一种(int, double, bool, string)。我不认为我可以只专门化构造函数,而且我宁愿不专门化每个类型的整个类。下面代码的问题是stringstream在遇到空格时停止输出:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <typename Ty>
struct Test
{
    Ty value;
    Test(string str) {
        stringstream ss;
        ss.str(str);
        ss >> value;
    }
};

int main()
{
    Test<int> t1{"42"};
    Test<double> t2{"3.14159"};
    Test<string> t3{"Hello world"};
    cout << t1.value << endl << t2.value << endl << t3.value << endl;
    return 0;
}
上面代码的输出是:
42
3.14159
Hello

而不是"Hello world"。有没有办法让stringstream不停止在空白,或其他一些设备,将做任意转换像我需要?

这对我有用。只需在通用实现之前声明一个特殊实现:

#include <iostream>
#include <string>
#include <sstream>
template<typename T>
struct Test {
    T value;
    Test(std::string);
};
template<>
inline Test<std::string>::Test(std::string str) {
    value = str;
}
template<typename T>
inline Test<T>::Test(std::string str) {
    std::stringstream ss;
    ss.str(str);
    ss >> value;
}
int main() {
    Test<int> t1{"42"};
    Test<double> t2{"3.14159"};
    Test<std::string> t3{"Hello world"};
    std::cout
        << t1.value << std::endl
        << t2.value << std::endl
        << t3.value << std::endl;
    return 0;
}