如何自定义转换模板参数
How to customly convert template arguments
假设我解析一个文件,并将得到一个字符串向量作为结果,其中包含各种数据类型。我现在正在寻找一个类似的函数:
template<typename T>
T convertToType(const std::string& str);
它可以进行这种转换。理想情况下,我应该能够以某种方式提供自己的转换函数,即如果T是自己的复杂类型。有没有办法避免每次都必须将其作为参数传递?
我在想某种:
if(typeof(T) == double)
std::stod(str)
// ...
else
throw std::logical_error("Type not supported yet!");
另一种选择是为每个类型编写一个模板专用化,但如果我必须再次为每个类型指定模板函数,这似乎会使模板函数的使用变得毫无用处。。。
这将把约阿希姆的评论变成一个答案
使用std::istringstream
并让输入运算符>>
处理它。
std::istringstream iss(str);
T result;
if (!(iss >> result)) {
throw std::logical_error("Type conversion failed!");
}
return result;
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何将向量中的可变参数转换为参数的持有者?
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 将空*参数转换为各种类型的参数是UB吗?
- 将可变参数模板参数转换为 JSON 字符串
- C++ 如何将函数参数转换为字符串
- 功能指针参数参数转换为const
- 避免对模板运算符过载的隐式参数转换
- 将C 方法参数转换为模板参数会因编译错误而失败
- 将参数转换为lpwstr createProcess
- 在与时间一起使用 srand 时,如果我没有time_t参数明确地将参数转换为无符号的 int 参数,这有关系吗?
- 将C++整型模板参数转换为整型"longer"型
- 将参数转换为目标类型时,复制用于直接初始化的构造函数省略
- 将命令行参数转换为qimage
- 将可变数量的参数转换为明确的数量
- SDL 方法,参数转换
- 通过错误检查将参数转换为整数
- 功能参数转换为儿童类C
- 参数转换在课堂上
- 在窗口上将格式化的 C 字符串和参数转换为 wstring