C ++创建一个标头,其中包含用于重载ostream的模板

时间:2016-04-26 16:01:57

标签: c++ templates header friend ostream

我试图让它工作,但它会出现一条错误消息

C2473 " operator << looks like a function definition but there is no parameter list."

基本上,这是一个头文件,我想为一个类声明一个名称空间和一个模板,同时覆盖&lt;&lt;运营商。

请帮忙! (我也是stackoverflow的新手,这是我的第一个问题):)

#ifndef header
#define header

namespace nmsp{
  template <class T> 
  class expt; //forward declaration of class, so friend function can be defined as a template
  template <class T> 
  std::ostream& operator << (std::ostream& os, const expt <T> &input);


template <class T> 
class expt {


    friend std::ostream& operator << (std::ostream& os, const expt <T>& input);

private: 
    T *data;
public: 
    expt() { data = null; }

};

template <class T> 
std::ostream& nmsp:: operator << (std::ostream& os, const expt <class T>& input) {
    //....
}
}
}
#endif

1 个答案:

答案 0 :(得分:0)

这是您的固定代码(请参阅评论):

namespace nmsp{
  template <class T> 
  class expt; // forward declaration of class, so friend function can be 
              // defined as a template
  template <class T> 
  std::ostream& operator << (std::ostream& os, const expt <T> &input);


template <class T> 
class expt {

    // templated friend declarations don't inherit the outer 
    // class template parameters, you need to make them a template separately
    template <class U>
    friend std::ostream& operator << (std::ostream& os, const expt <U>& input);

private: 
    T *data;
public: 
    expt() { data = nullptr; }
                 // ^^^^^^^ null isn't a thing

};

}

// Move the definition out of the namespace
template <class T> 
std::ostream& nmsp:: operator << (std::ostream& os, const expt <T>& input) {
                                                            // ^^^ drop class
    //....
    return os;
}
// Remove the extra }

Live Demo