【问题标题】:boost::lexical_cast not recognizing overloaded istream operatorboost::lexical_cast 无法识别重载的 istream 运算符
【发布时间】:2015-01-15 09:00:03
【问题描述】:

我有以下代码:

#include <iostream>
#include <boost\lexical_cast.hpp>

struct vec2_t
{
    float x;
    float y;
};

std::istream& operator>>(std::istream& istream, vec2_t& v)
{
    istream >> v.x >> v.y;

    return istream;
}

int main()
{
    auto v = boost::lexical_cast<vec2_t>("1231.2 152.9");

    std::cout << v.x << " " << v.y;

    return 0;
}

我从 Boost 收到以下编译错误:

错误 1 ​​错误 C2338:目标类型既不是 std::istreamable nor std::wistreamable

这似乎很简单,过去一个小时我一直在用头撞桌子。任何帮助将不胜感激!

编辑:我使用的是 Visual Studio 2013。

【问题讨论】:

  • 浪费了我一天的时间来处理这个问题;(

标签: c++ boost operator-overloading istream lexical-cast


【解决方案1】:

有两阶段查找在起作用。

您需要使用 ADL 启用重载,所以lexical_cast 会在第二阶段找到它。

所以,你应该把重载移到命名空间mandala

这是一个完全固定的例子(你也应该使用std::skipws):

Live On Coliru

#include <iostream>
#include <boost/lexical_cast.hpp>

namespace mandala
{
    struct vec2_t {
        float x,y;
    };    
}

namespace mandala
{
    std::istream& operator>>(std::istream& istream, vec2_t& v) {
        return istream >> std::skipws >> v.x >> v.y;
    }
}

int main()
{
    auto v = boost::lexical_cast<mandala::vec2_t>("123.1 15.2");
    std::cout << "Parsed: " << v.x << ", " << v.y << "\n";
}

【讨论】:

  • 我倾向于说"it's a hyperlink"
  • 编辑了我的帖子,消除了我之前使用的 mandala 命名空间。发生同样的错误。
  • @cmbasnett Live On Coliru 我很确定存在观察错误(或严重损坏的编译器)
  • 直接将 Coliru 上的代码复制粘贴到 Visual Studio 2013 中并编译它会产生相同的错误。 :S
  • 我也在运行 VS 2013,它为我编译。你有更新 4 吗?
猜你喜欢
  • 2021-12-16
  • 2015-02-16
  • 1970-01-01
  • 2020-08-25
  • 2013-10-10
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
相关资源
最近更新 更多