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;
}
};
开发者_如何学Cint main()
{
A a;
a << 4;
system("pause");
}
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):
- http://connect.microsoft.com/VisualStudio/feedback/details/649496/visual-c-doesnt-respect-the-access-modifier-for-operator-member-function-templates
from the comments, the fix appears to be already made to an internal compiler build.
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. ]
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.
精彩评论