3

Assuming following code. There is class MyStream witch has template overloaded operator <<. There also is globally overloaded operator MyStream& operator << (MyStream&, const MyClass&). The confusing thing is generating (by compiler) different methods for two almost identical situations (see body of main() function). I supposed that global operator should be used in both cases but it isn't. Why so?

#include <iostream>

class MyStream;
class MyClass;
MyStream& operator << (MyStream& stream, const MyClass&);

class MyStream
{
public:
    template <typename T>
    MyStream& operator << (const T&)
    {
        std::cout << __FUNCTION__ << " " << typeid(T).name() << std::endl;
        return *this;
    }
};

class MyClass
{
};

MyStream& operator << (MyStream& stream, const MyClass&)
{
    std::cout << __FUNCTION__ << " " << typeid(MyClass).name() << std::endl;
    return stream;
}

int main(int, char**)
{
    // 1. Used globally defined operator for MyClass
    MyStream() << int() << MyClass();
    std::cout << std::endl;

    // 2. Template instantiation
    MyStream() << MyClass();

    std::cin.get();
    return 0;
}

Output of program compiled with Microsift Visual C++ Compilers 9.0 (x86):

MyStream::operator << int
operator << class MyClass

MyStream::operator << class MyClass
tim
  • 788
  • 4
  • 14
  • 1
    Nice question! Short code, and a clean problem statement. I wish all questions here were as clearly formulated as this one! – Sjoerd Feb 18 '12 at 14:03

1 Answers1

5
// 2. Template instantiation
 MyStream() << MyClass();

In this case, the expression MyStream() creates a temporary object (a rvalue) which cannot be bound to non-const reference, so the compiler chooses the member function template, because in order to call the free function, the temporary object must be passed as first argument to the function, which is not possible here, as the type of first parameter of the free function is non-const reference. So MyStream << MyClass() invokes member function.

But when you write this:

// 1. Used globally defined operator for MyClass
MyStream() << int() << MyClass();

It first invokes the member function passing int(), and the member function returns an object of type MyStream& which now can be passed to free function as first argument (as it is no more a rvalue, it is now a lvalue), then it invokes the free function, passing object of type MyStream& as first argument and MyClass() as second argument.

This is interesting, and a similar thing happens here:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851