c++ - 如何最好地处理从 const char * 转换为模板类型
问题描述
我有一个模板函数,我需要在其中将 const char * 转换为我的模板值。我知道这个 const char * 最初是从 ascii 文本文件中读取的。我当前的代码如下所示:
template <typename T>
bool Get(T &value, std::string const &query, T const &default)
{
const char* result = DataHandler.GetValue(query);
if (result != NULL)
{
value = static_cast<T>(result); //Here is the issue
return true;
}
value = default
return false;
}
以 int 为例,我得到了错误
错误 C2440:“static_cast”:无法从“const char *”转换为“int”
有没有办法可以无缝地将 char* 转换为我的类型 T,我在 SO 上找不到答案。
在最坏的情况下,我可以为我期望的 10 种类型提供一个案例,如果不是其中一种,我会给出错误,但如果可能的话,我宁愿不这样做。
解决方案
有没有办法可以无缝地将 char* 转换为我的类型 T,
不。
没有办法使从字符串到类型的转换自动适用于所有类型。必须为每个类实现这种转换。通常,它是通过实现流提取操作符>>
来完成的std::istream
。内置类型如int
和一些标准类型如std::string
已经有这样的操作符。然后你可以做例如:
std::istringstream istream(result);
int i;
istream >> i;
推荐阅读
- c - 我在下面的行中收到错误。怎样才能纠正呢?还是我实施了错误的方式?
- sharepoint - 在 MS Exchange 中构建 Web 部件
- html - req.body 没有使用更新
- android - 创建新 TableRow 时出现“上下文”错误
- javascript - 在 ts 中映射元组?
- azure - 对于具有托管标识的 Azure 应用服务,如何检索客户端 ID
- jquery - Ajax 请求作为 GET 请求而不是 PUT 请求传递
- javascript - MutationObserver 和 window.onresize 永远不会停止,即使工作已经完成
- python - 如何获取数组中的一些元素
- r - 加速搜索匹配两个条件的行,例如 R 中的 which(...&...)