C ++: friend function in template class for operator <<

What is the correct way to declare a friend function of a template class (for the std :: ostream & <<operator) in a .cpp file ?

My current implementation does not work:

// MyTest.h
template<class T, unsigned int TSIZE> class MyTest
{
    inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs);
};

// MyTest.cpp
template<class T, unsigned int TSIZE> inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs)
{
    // IMPLEMENTATION
}

Many thanks!

+5
source share
2 answers

To reference operator<< <T, TSIZE>how you do this, this is a specialized specialization, the declaration of the primary template must be visible. In turn operator<<, an ad is required MyTestbecause it is displayed as a parameter.

// Declare MyTest because operator<< needs it
template<class T, unsigned int TSIZE> class MyTest;

// Declare primary template
template<class T, unsigned int TSIZE>
inline std::ostream& operator<<(std::ostream& lhs, const MyText<T, TSIZE>& rhs);

template<class T, unsigned int TSIZE> class MyTest
{
    // Specialization MyTest<T, TSIZE> only declares
    // specialization operator<< <T, TSIZE> as friend
    // Note that you can just use '<>' to designate the specialization,
    // template parameters are deduced from the argument list in this case
    inline friend std::ostream& operator<< <> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs);
};

. , operator<< , .

, , , MyTest<T, TSIZE>, , , MyTest<T, TSIZE>.

// in MyTest definition
template<typename U, unsigned USIZE>
inline friend std::ostream& operator<<(std::ostream& lhs, const MyTest<U, USIZE>& rhs);

( ).

, , . - -, .

// in MyTest definition
friend std::ostream& operator<<(std::ostream& lhs, MyTest const& rhs)
{ /* implementation */ }

(, &ns::operator<< , ), ADL.

+7

, . , :

// Some template class.
template<class T, unsigned int TSIZE> class MyTest { };

// Some template function.
template<class T, unsigned int TSIZE> std::ostream& operator<< (std::ostream &lhs, const MyTest<T, TSIZE> &rhs)
{
    // IMPLEMENTATION
}

, My test. :

template<class T, unsigned int TSIZE> class MyTest
{
    template<class T1, unsigned int TSIZE1> 
    friend std::ostream& operator<< (std::ostream &lhs, const MyTest<T1, TSIZE1> &rhs);
};

friend, , .

0

All Articles