模板类对象的<<运算符重载

<< operator overloading for template class object

本文关键字:lt 运算符 重载 对象      更新时间:2023-10-16

我已经编写了一个类似于bitset类的C++STL:

template<size_t N>
class bitset {
public:
 ...........
 friend std::ostream& operator << (std::ostream &, bitset<N> const&);
private:
 ..........
};
// end of class
template<size_t N>
std::ostream& operator << (std::ostream &os, bitset<N> const& rhs) {
    ............
    .........
    return os;
}

我正试着这样使用它:

bitset<5> foo; // success
std::cout << foo << std::endl; // fail

错误信息是-

undefined reference to `operator<<(std::ostream&, bitSet<5u> const&)

到底出了什么问题?

你朋友的声明也必须是一个模板,就像定义一样:

template <size_t N>
class bitset {
public:
    template <size_t M>
    friend std::ostream& operator << (std::ostream &, bitset<M> const&);
};
template <size_t M>
std::ostream& operator << (std::ostream &os, bitset<M> const& rhs) {
    return os;
}

或者,您可以直接在类范围内声明operator<<

template<size_t N>
class bitset {
public:
    friend std::ostream& operator << (std::ostream & os, bitset const&) {
        return os;
    }
};

这里给出了您的问题的一些可能答案。

除了Piotr S.的答案外,您还可以预先声明函数模板:

template<size_t N> class bitset;
template<size_t N> std::ostream& operator << (std::ostream &, bitset<N> const&);
//now comes your class definition