boost::lexical_cast not recognizing overloaded istream operator

2.9k views Asked by At

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 are 1 answers

9
sehe On BEST ANSWER

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

enter image description here