Question

This compiles with out problems in VS 2009? Am I stupid? GCC gives a warning, that the template is private....? What am I missing?

#include <iostream>

using namespace std;

class A
{
private:
    template<typename T>
    A& operator<<(const T & v)
    {
        cout << v << endl;
        return *this;
    }
};

int main()
{
   A a;
   a << 4;
   system("pause");
}
Was it helpful?

Solution

This code should not compile - this is a bug (or silly extension) in VS. GCC should refuse it as well. The operator is inaccessible in the scope it is used.

Comeau treats this correctly:

"ComeauTest.c", line 28: error: function "A::operator<<(const T &) [with T=int]"
          (declared at line 14) is inaccessible
     a << 4;

EDIT: A relevant standard snippet, from 13.3/1

[Note: the function selected by overload resolution is not guaranteed to be appropriate for the context. Other restrictions, such as the accessibility of the function, can make its use in the calling context ill-formed. ]

OTHER TIPS

Microsoft acknowledges the bug and claims it will be fixed in the next major release for the compiler (which I read as VC11/VS-whatever-is-after-2010 - probably not a service pack for VC10/VS2010):

from the comments, the fix appears to be already made to an internal compiler build.

No, you're not stupid - it's broken code and should be rejected. The Comeau compiler (http://www.comeaucomputing.com/tryitout) does correctly reject it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top