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 function
main':
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_; } //... };