如何将std::string转换为构造函数中几种类型中的任何一种
How to convert std::string to any of several types in constructor?
我有下面的类模板,它有一个成员变量,其类型由模板参数决定。我想在构造函数中初始化这个成员的值,它只接受一个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;
}
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- 哗啦��错误:无法识别任何一组可以驱动指定关节的控制器
- 如何在同一个模板功能上专门化几种类型?
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP
- Qt - 在没有正则表达式的情况下,将 QString 拆分为几种类型的空格
- 从文件中读取未签名字符的几种不同方法
- C++阿特金的筛子返回了几种复合材料
- 最简单的方法来封装几个语句中的几种语句
- 一些应用程序是如何用几种编程语言制作的
- 在 C++Amp 中并行执行的几种算术运算
- 链表的几种实现 - C++
- 几种特定方法或一种通用方法
- Qt-拆分一个QString,使用几种类型的空白作为分隔符
- 将 void* 强制转换为仅在运行时已知的几种类型
- C ++中的几种分配内存方法有什么区别
- 在编程中,这两项任务中的任何一项都有算法方法吗
- LNK2019错误-未找到外部符号.尝试了几种解决方案
- 声明空/默认构造函数的几种方法之间的差异
- 以几种组合替换
- 如何将std::string转换为构造函数中几种类型中的任何一种