首页 > 解决方案 > 如何最好地处理从 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 种类型提供一个案例,如果不是其中一种,我会给出错误,但如果可能的话,我宁愿不这样做。

标签: c++templatestype-conversion

解决方案


有没有办法可以无缝地将 char* 转换为我的类型 T,

不。

没有办法使从字符串到类型的转换自动适用于所有类型。必须为每个类实现这种转换。通常,它是通过实现流提取操作符>>来完成的std::istream。内置类型如int和一些标准类型如std::string已经有这样的操作符。然后你可以做例如:

std::istringstream istream(result);
int i;
istream >> i;

推荐阅读