2

I'm trying to figure out why I cannot call the overloaded operator << as member function just as I call the operator+ as member function.

#include "pch.h"
#include <iostream>

using namespace std;

class A
{
    int x;
public: A(int i = 0) { x = i; }
        A operator+(const A& a) { return x + a.x; }
        template <class T> ostream& operator<<(ostream&);
};
template <class T>
ostream& A::operator<<(ostream& o) { o << x; return o; }
int main()
{
    A a1(33), a2(-21);
    a1.operator+(a2);
    a1.operator<<(cout); // Error here
    return 0;
}
  • 1
    Because ostream should be a left-hand side. – Igor R. Jun 08 '19 at 20:25
  • 1
    Your `operator<<` is a function template but `T` isn't being deduced or provided. – David G Jun 08 '19 at 20:26
  • 2
    Read this: [What are the basic rules and idioms of operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading), paying particular attention to the common operator section, and with that "Bitshift Operators (used for Stream I/O)". I somewhat suspect you're trying to shove a square peg in a round hole, and got off-track awhile ago. – WhozCraig Jun 08 '19 at 20:28
  • @IgorR. It _should_ be, but that's not why _this_ approach fails. – Lightness Races in Orbit Jun 08 '19 at 20:29

1 Answers1

7

Because you made the operator a function template and the function parameter is not of the template type. As a result, the template parameter cannot be resolved. You need to call it with a template parameter, for example:

a1.operator<< <void>(cout);

But that's useless, since the template parameter is not used. You either need to have T be the type of the function parameter:

template <class T> ostream& operator<<(T&);

Or just make it a normal function, since it doesn't look like you need it to be a template:

ostream& operator<<(ostream& o);
Nikos C.
  • 50,738
  • 9
  • 71
  • 96