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

时间:2014-10-15 08:26:05

标签: c++ templates c++11 stl bitset

我编写了一个类似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&)

实际上有什么问题?

2 个答案:

答案 0 :(得分:5)

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

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;
    }
};

答案 1 :(得分:3)

您的问题的一些可能答案是here

除了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