我有以下类模板,它有一个成员变量,其类型由template参数决定。我想在构造函数中初始化此成员的值,只需要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
代替&#34; Hello world&#34;。是否有某种方法可以让stringstream
不停留在空白处,或者其他一些会像我需要那样进行任意转换的设备?
答案 0 :(得分:1)
这对我有用。只需在通用实现之前声明一个特殊的实现:
#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;
}
这是一个ideone工作示例。