gpt4 book ai didi

c++ - 如何自定义转换模板参数

转载 作者:行者123 更新时间:2023-11-30 05:45:04 25 4
gpt4 key购买 nike

假设我解析了一个文件,并将得到一个包含各种数据类型的字符串 vector 。我现在正在寻找类似以下的功能:

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!");

另一种选择是为每种类型编写模板特化,但如果我必须再次为每种类型指定模板函数,这似乎会使模板函数的使用变得毫无用处...

最佳答案

这会将 Joachim 的评论变成答案。

使用 std::istringstream 并让输入运算符 >>> 处理它。

std::istringstream iss(str);
T result;
if (!(iss >> result)) {
throw std::logical_error("Type conversion failed!");
}
return result;

关于c++ - 如何自定义转换模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29520214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com