C++ 重载模板外模板类的输出流运算符

C++ 重载模板外模板类的输出流运算符,c++,templates,operator-overloading,C++,Templates,Operator Overloading,我想重载输出流操作符 有人能举一个简单的例子,说明输出流操作符如何停下来想一想:“它真的需要成为朋友吗?”@BoBTFish我不确定答案。我曾经在我的非模板类中将它声明为朋友。它是否使用任何private成员数据或函数?一定要吗?非常感谢你,迈克。这就是我想要的。我明白了。 template <typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::ve

我想重载输出流操作符


有人能举一个简单的例子,说明输出流操作符如何停下来想一想:“它真的需要成为
朋友吗?”@BoBTFish我不确定答案。我曾经在我的非模板类中将它声明为朋友。它是否使用任何
private
成员数据或函数?一定要吗?非常感谢你,迈克。这就是我想要的。我明白了。
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
  MyContainer():p(_MaxSize){};
  std::ostream& operator<<(MyContainer<T,_MaxSize,Policy,Container>& obj){ };
private:
  Container p;
};
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
  MyContainer():p(_MaxSize){};
  friend std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj);
private:
  Container p;
};

template
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj)
{
};
warning: friend declaration ‘std::ostream& operator<<(std::ostream&, MyContainer<T, _MaxSize, Policy, Container>)’ declares a non-template function [-Wnon-template-friend]
tempstruct.cc:39:97: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
// Declare the class template, because we need it to declare the operator
template <typename,int,template <class C> class,typename> class MyContainer;

// Declare the operator, because (as the error says) templates must be declared
// in the namespace before you can declare them friends. At this point, we can't
// define the operator, since the class template is incomplete.
template 
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream&,MyContainer<T,_MaxSize,Policy,Container>);

// Define the class template
template
<typename T,int _MaxSize=10,template <class C> class Policy=NoCheck,typename Container=std::vector<T>>
class MyContainer : public Policy<T>
{
public:
  MyContainer():p(_MaxSize){};

  // Include <> to indicate that this is the template
  friend std::ostream& operator<< <>(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj);
private:
  Container p;
};

// Finally define the operator
template
<typename T,int _MaxSize,template <class C> class Policy,typename Container>
std::ostream& operator<<(std::ostream& out,MyContainer<T,_MaxSize,Policy,Container> obj)
{
  // print some stuff
};