Вопрос

I am trying to overload operator>> in order to extract type T from istream x; and insert into ostream y;, i.e. x >><T> y;.

With

template<class T> istream& operator>>(istream& is, ostream& os)
{
    T a;
    is >> a;
    os << a;
    return is;
}

the prefix notation operator>><string>(x,y); compiles, but postfix notation x >><string> y; fails to compile with

test.cpp:29:9: error: expected expression
    x >><string> y;
        ^
test.cpp:29:10: error: unexpected type name 'string': expected expression
    x >><string> y;
         ^
2 errors generated.

and i guess the >><T> notation is just not valid.

Just curious if there is a way to get the postfix version to compile? Or maybe some thoughts whether an extract/insert operator makes sense at all?

Это было полезно?

Решение

Short answer, no. Operator overloading proceeds according to strict grammatical rules, so for any binary operator @, the expression a @ b considers overloaded functions (a).operator@(b) and operator@(a, b).

The right thing in your case is to make a wrapper object:

template <typename T> class pass
{
    std::ostream & os_;
public:
    pass(std::ostream & os) : os_(os) {}

    friend std::istream & operator>>(std::istream & is, pass & p)
    {
        T x;
        if (is >> x) { p.os_ << x; }
        return is;
    }

    friend std::istream & operator>>(std::istream & is, pass && p)
    {
        return is >> p;
    }
};

Usage:

std::cin >> pass<int>(std::cout);

Note that we're taking the pass<T> object by rvalue reference to allow this construction.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top