Search code examples
c++templatesc++11stlbitset

<< operator overloading for template class object


I have written a C++ STL like bitset class:

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

And I am trying to use it like this:

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

And the error message is -

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

What's the problem actually?


Solution

  • Your friend's declaration must be a template as well, just like the definition is:

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

    Alternatively, you could declare the operator<< directly within the class scope:

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