<<< Function template example | Index | Inheritance vs. templates >>> |
#include <iostream>
using namespace std;
// Forward declare class template
template < typename ValueT > class Container;
// Forward declare function template
template < typename ValueT > ostream& operator<<( ostream& os, Container< ValueT > const& v );
template < typename ValueT >
class Container {
public:
// This friend declaration is a template of ValueT
// function because of the extra <> after the name:
friend ostream& operator<< <>( ostream& os, Container< ValueT > const& v );
private:
ValueT m_data;
};
int main()
{
Container< int > vect_i;
cout << vect_i;
return 0;
}
template < typename ValueT > ostream& operator<<( ostream& os, Container< ValueT > const& v )
{
os << v.m_data;
return os;
}
If we left out the < > part, we would get a
Warning: friend declaration declares a non-template function if this is not what you intended, make sure the function template has already been declared and add <> after the function name here. Linker error: unresolved external symbol...
<<< Function template example | Index | Inheritance vs. templates >>> |