boost::lexical_cast not recognizing overloaded istream operator

好久不见. 提交于 2019-12-23 09:39:12

问题


I have the following code:

#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;
}

I am receiving the following compile error from Boost:

Error 1 error C2338: Target type is neither std::istreamable nor std::wistreamable

This seems straightforward enough, and I have been hitting my head against the desk for the last hour. Any help would be appreciated!

EDIT: I am using Visual Studio 2013.


回答1:


There's 2-phase lookup at play.

You need to enable the overload using ADL, so lexical_cast will find it in the second phase.

So, you should move the overload into namespace mandala

Here's a completely fixed example (you should also use 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";
}



来源:https://stackoverflow.com/questions/26989803/boostlexical-cast-not-recognizing-overloaded-istream-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!