【问题标题】:Type conversion using templates has odd behaviour使用模板进行类型转换有奇怪的行为
【发布时间】:2012-10-05 09:00:43
【问题描述】:

我有一个函数,旨在将配置文件中的字符串转换为各种不同的类型。当使用字符串流时,需要插入一个特殊情况来处理布尔值,因为“假”等于真。

单独的函数并不是一个真正的选择,因为它需要对我们正在使用的每种类型进行类型检查。

该函数在以前是类的一部分时可以正常工作,但是为了使其更有用,它被移到了自己的启动函数中。该函数在返回 true 时抛出 2 个错误。返回 false 符合预期。

下面是代码示例和visual studio抛出的错误。

template <typename T>
static T StringCast(string inValue)
{
    if(typeid(T) == typeid(bool))
    {
        if(inValue == "true")
            return true;
        if(inValue == "false")
            return false;
        if(inValue == "1")
            return true;
        if(inValue == "0")
            return false;
        return false;
    }

    std::istringstream stream(inValue);
    T t;
    stream >> t;
    return t;
}

错误 1 ​​错误 C2664: 'std::basic_string<_elem>::basic_string(const std::basic_string<_elem> &)' : 无法将参数 1 从 'bool' 转换为 ' const std::basic_string<_elem> &'

错误 2 错误 C2664: 'std::basic_string<_elem>::basic_string(const std::basic_string<_elem> &)' : 无法将参数 1 从 'bool' 转换为 ' const std::basic_string<_elem> &'

【问题讨论】:

  • ideone.com/1ZqKf 编译正常。
  • 称之为 bool b = StringCast("true");在 VS2010 下工作正常
  • @luskan 不要误导 OP:ideone.com/0AKMJ
  • 它在另一个模板函数中使用。模板 T INIParser::GetValue(string key) { return StringCast(this->iniData[key]); }
  • @LuchianGrigore 不要误导 OP ideone.com/0AKMJ

标签: c++ string templates boolean


【解决方案1】:

如果您想对 bool 进行专业化 - 那么只需为 bool 定义专业化。你的方法是不可能的。使用下面的正确方法:

template <typename T>
T StringCast(string inValue)
{
    std::istringstream stream(inValue);
    T t;
    stream >> t;
    return t;
}

template <>
bool StringCast<bool>(string inValue)
{
        if(inValue == "true")
            return true;
        if(inValue == "false")
            return false;
        if(inValue == "1")
            return true;
        if(inValue == "0")
            return false;
        return false;
}

int main() {
   int a = StringCast<int>("112");
   bool b = StringCast<bool>("true"); 
}

【讨论】:

  • 我们已经成功地进行了一些更改以消除链接器重定义错误,但非常感谢。
猜你喜欢
  • 2014-10-23
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多