Re: Strange compiler error w.r.t 'friend ostream& operator<<
<>(ostream&, ...)'
abhay.bu...@gmail.com wrote:
I have the following piece of code ...
NOTE: I have intentionally qualified 'ostream' and 'cout' with 'std::'
for the purposes of the example
#include<iostream>
using namespace std;
template<class T>
class SomeClass{
public:
SomeClass(const T& a) : member(a)
{
}
friend std::ostream& operator<< <>(std::ostream &,SomeClass <T>&);
private:
T member;
};
template <typename T>
std::ostream& operator<< (std::ostream &os, SomeClass<T>&some)
{
os<<"( " << some.member <<") ";
return os;
}
int main(int argc, char* argv[])
{
SomeClass<int> sc(5);
std::cout << sc;
return 0;
}
This compiles fine.
The above doesn't compile with gcc (4.3.3)
(either with and without 'using namespace std'):
yyy.cc: In instantiation of =91SomeClass<int>':
yyy.cc:27: instantiated from here
yyy.cc:11: error: template-id =91operator<< <>' for =91std::ostream&
operator<<(std::ostream&, SomeClass<int>&)' does not match any
template declaration
yyy.cc: In function =91std::ostream& operator<<(std::ostream&,
SomeClass<T>&) [with T = int]':
yyy.cc:28: instantiated from here
yyy.cc:13: error: =91int SomeClass<int>::member' is private
yyy.cc:20: error: within this context
If I forward-declare SomeClass and operator<<, it compiles fine
(both with and without 'using namespace std'):
#include<iostream>
//using namespace std;
template <class T>
class SomeClass;
template <class T>
std::ostream& operator<<(std::ostream &,SomeClass <T>&);
template<class T>
class SomeClass{
public:
SomeClass(const T& a) : member(a)
{
}
friend std::ostream& operator<< <>(std::ostream &,SomeClass
<T>&);
private:
T member;
};
template <typename T>
std::ostream& operator<< (std::ostream &os, SomeClass<T>&some)
{
os<<"( " << some.member <<") ";
return os;
}
int main(int argc, char* argv[])
{
SomeClass<int> sc(5);
std::cout << sc;
return 0;
}
[skip Comeau and MSVC errors]
Why??
I have no idea why the using directive would change anything.