The compiler does not create a templated ostream << statement

I have a class defined in my head as:

template <typename T> class MyClass
{
   template <typename U> friend std::ostream& operator<<(std::ostream& output, const MyClass<U>& p);
   public:
      ...
}

In the implementation file, I:

template <typename U> std::ostream& operator<<(std::ostream& output, const MyClass<U>& m)
{
   output << "Some stuff";
   return output;
}

That everything looks pretty kosher. However, when I try to use this operator (i.e., Std :: cout <MyClass ()), I get the following linker error:

Undefined symbols: std::basic_ostream<char, std::char_traits<char> >& operator<< <InnerType>(std::basic_ostream<char, std::char_traits<char> >&, MyClass<InnerType> const&)

I am surprised that the compiler did not automatically create this for me ... Any suggestions as to what I am doing wrong?

+3
source share
2 answers

In the implementation file, I:

. . - ++. , .

, , ++ , . , ( ), .

++ export . no ( ?), , / .

+8

- :

#include <iostream>
using namespace std;
template <typename T> struct MyClass {

    friend ostream & operator << ( ostream & os, MyClass<T> & c ) {
        os << "MyClass\n";
        return os;
    }
};

int main() {
    MyClass <int> c;
    cout << c;
}
+1

Source: https://habr.com/ru/post/1703238/


All Articles