1

Why does the following code not compile (linker error, unresolved external symbol, class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class cClass<int> const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBV?$cClass@H@@@Z))

#include <iostream>

template <class Type> class Class{
    public:
        friend std::ostream& operator<<(std::ostream& Stream, const Class& Op);
};

template <class Type> std::ostream& operator<<(std::ostream& Stream, const Class<Type>& Op){
    return(Stream);
}

int main(){
    Class<int> A;

    std::cout << A;

    return(0);
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
Mario
  • 123
  • 5
  • Look up the semantics of friend functions. You would have to declare the friend function inside the class as template as well. – DeiDei Nov 29 '15 at 13:42

1 Answers1

5

This line:

friend std::ostream& operator<<(std::ostream& Stream, const Class& Op);

Should be:

template <class T> friend std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op);
skypjack
  • 49,335
  • 19
  • 95
  • 187
  • Thanks, it works. But what if I want to have interface and implementation in different files? – Mario Nov 29 '15 at 13:59
  • 1
    As stated [here](http://en.cppreference.com/w/cpp/language/templates): *The definition of a template must be visible at the point of implicit instantiation, which is why template libraries typically provide all template definitions in the headers*. – skypjack Nov 29 '15 at 14:05
  • @Mario you can #include ".cpp"` at the end of file, before the header protection `#endif`, and move your template implementations to your cpp file – Varaquilex Nov 29 '15 at 14:06
  • 1
    @Varaquilex to include *.cpp* files is far from being a good practice. – skypjack Nov 29 '15 at 14:08
  • @skypjack then how do you keep your header file without template function implementations? Can you elaborate more on why including template function implementations in header file its far from being a good practice? – Varaquilex Nov 30 '15 at 01:10
  • I've never said that to include template function implementation is a bad practice, I've said that to include .cpp files is far from being a good one. If you want to separate definition and implementation of a template, use at least some sort of .impl or .td or whatever files, so that the reader is not forced to open each .cpp and .h file to understand how your code and compilation units are organized. – skypjack Nov 30 '15 at 07:08
  • 1
    See also [here](https://isocpp.org/wiki/faq/templates) for further information about templates. – skypjack Nov 30 '15 at 07:10
  • Also, on SO, see [that question](http://stackoverflow.com/q/495021/4987285) for further details. – skypjack Nov 30 '15 at 22:19