Kai*_*dul 1 c++ templates stl bitset c++11
我写过类似C++的STL bitset
:
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;
}
Run Code Online (Sandbox Code Playgroud)
我试图像这样使用它:
bitset<5> foo; // success
std::cout << foo << std::endl; // fail
Run Code Online (Sandbox Code Playgroud)
错误信息是 -
undefined reference to `operator<<(std::ostream&, bitSet<5u> const&)
Run Code Online (Sandbox Code Playgroud)
实际上有什么问题?
您朋友的声明也必须是模板,就像定义是:
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;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以operator<<
直接在类范围内声明:
template<size_t N>
class bitset {
public:
friend std::ostream& operator << (std::ostream & os, bitset const&) {
return os;
}
};
Run Code Online (Sandbox Code Playgroud)