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

标签 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&)

究竟是什么问题?

最佳答案

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

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

关于c++ - << 模板类对象的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26377870/

相关文章:

c++ - "may be used uninitialized in this function [-Wmaybe-uninitialized]"

c++ - 有没有更好的方法来重写这个丑陋的 switch 和 if 语句组合?

c++ - 在模板类中重载模板方法

接收 std::vector 作为参数的 C++ 模板函数

c++ - 在 Visual C++ Express 中构建 C 代码

c++ - 渲染透明物体

c++ - 如何从模板创建带有 C 链接的函数?

c++ - 编译但每次都崩溃#class template c++

c++ - `getopt` 的段错误

c++ - 程序在 C++11 中使用条件变量进入死锁