如何自定义转换模板参数

How to customly convert template arguments

本文关键字:参数 转换 自定义      更新时间:2023-10-16

假设我解析一个文件,并将得到一个字符串向量作为结果,其中包含各种数据类型。我现在正在寻找一个类似的函数:

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;