1

I am reading about STL containers so when I got to the relational operators how work with them: I found that the containers use the Element Type Relational Operator when two containers of the same type are compared, How ever I'd like to break their rule and define a relational operator that doesn't depend on the operation provided by the element type.

#include <iostream>



template<class T>
class Vector {
    public:
        using size_type = unsigned int;

        Vector() = default;
        Vector(size_type, T = T());

        size_type size()const { return sz_; }
        T* elem()const { return elem_; }

        ~Vector();

        friend bool operator < (const Vector<T>& x, const Vector<T>& y);

    private:
        T* elem_ = nullptr;
        size_type sz_ = 0;
};

template<class T>
Vector<T>::Vector(size_type sz, T x) :
    sz_(sz ? sz : 0),
    elem_(sz ? new T[sz] : nullptr) {
    for (size_type i{}; i != sz_; ++i)
        elem_[i] = x;
}

template<class T>
Vector<T>::~Vector() {
    delete[] elem_;
    sz_ = 0;
}


template<class T>
bool operator < (const Vector<T>& x, const Vector<T>& y) {
    return x.sz_ < y.sz_;
}


class A{
    public:

};



int main(){

    Vector<int> v1(7);
    Vector<int> v2(9);

    std::cout << (v1 < v2) << std::endl;

    Vector<A> v3(10);
    Vector<A> v4(12);

    std::cout << (v3 < v4) << std::endl;

}

But When I compile the program runs fine but if I define the < it doesn't work so I get link-time error complaining about the definition of:

/usr/bin/ld: /home/5jxZPM/prog-a06418.o: in functionmain': prog.cpp:(.text+0x5e): undefined reference to operator<(Vector<int> const&, Vector<int> const&)'

  • If I define it inside the class then it works fine!

    template<class T>
    class Vector {
        public:
            friend bool operator < (const Vector<T>& x, const Vector<T>& y){
                return x.sz_ < y.sz_;
            }
        //...
    };
    
Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 1
    Oh believe me, this gave me a headache when I ran into it. The friend declaration inside your class is declaring a friend function that is _not_ a template function. So it doesn't match with the template function outside. – Weak to Enuma Elish Aug 13 '19 at 22:14
  • Something tells me you're going to find [this question](https://stackoverflow.com/questions/18792565/declare-template-friend-function-of-template-class) an interesting read. – WhozCraig Aug 13 '19 at 22:15
  • @WeaktoEnumaElish:Thank you! I've solved it by declaring the friend as a template. – Itachi Uchiwa Aug 13 '19 at 22:28

0 Answers0