[C++] Operator Overloading (what's wrong?)

Started by
4 comments, last by aryx 14 years, 1 month ago
#include <iostream>

using namespace std;

template <class T>
class v
{
    public:
    friend std::ostream& operator<< <T>(ostream &,const v<T>&);

};
template <class T> ostream& operator<<(ostream &out,const v<T> & p)
{
    out << "test";
    return out;
}

int main()
{
    v<int> aaa;
    std::cout << aaa;
    return 0;
}


Quote:error: template-id `operator<< <int>' for `std::basic_ostream<char, std::char_traits<char> >& operator<<(std::basic_ostream<char, std::char_traits<char> >&, const v<int>&)' does not match any template declaration
Please point my english mistakes everytime you can.
Advertisement
Should:

friend std::ostream& operator<< <T>(ostream &,const v<T>&);

be:

friend std::ostream& operator<<(ostream &,const v<T>&);

???
Actually, I believe you should be "binding" the friend to a different template parameter than the class' template parameter, since it isn't a part of the class (forgive me if I am using the wrong terminology). What I mean is this:

#include <iostream>using namespace std;template <class T>class v{    public:    template <class U>    friend std::ostream& operator<<(ostream &,const v<U>&);};template <class T> ostream& operator<<(ostream &out,const v<T> & p){    out << "test";    return out;}int main(){    v<int> aaa;    std::cout << aaa;    return 0;}
That shouldn't matter, the compiler is simply confused because the definition and implementation do not match.
Shouldn't a stream operator be able to do what it needs with a class's public interface? Or rather, shouldn't a public interface supply whatever a stream operator might need? I don't think I've ever needed a stream operator to be a friend of the class it was printing.
Quote:Original post by chidj
That shouldn't matter, the compiler is simply confused because the definition and implementation do not match.


I'm no template expert, but I believe it does matter in this case since the friend function is a template function. Using your suggestion implies that the function is a non-template function specialized for the specific instantiation of T. This would mean writing the function for each type that you use with v. My suggestion explicitly specifies that the function is a template function. Nevertheless, I believe that my suggestion also allows operator<< to access the private members of a v<double> even if it were instantiated with a v<int>. Like I said, I'm no template expert but feel free to enlighten me if I'm wrong. I'm always up for learning!

Anyways, this GCC doc gives another possibility where you just simply use <> after the function name. This will prevent the issue I mentioned above. I don't know what the case may be for MSVS. Nevertheless, I'd suggest just going with theOcelot's advice to save yourself from possible future troubles.

This topic is closed to new replies.

Advertisement