C ++ STL: using a derived virtual class as "Strict weak order" for std :: sort ()

I hit the wall using std :: sort (). I have a pure virtual class (named Compare ) from which the calling method is called (named MyComp ). I use a pure virtual class for my prototype API:

 void Object::DoSort(Compare &comp) { std::sort(this->mKeys.begin(),this->mKeys.end(), comp); } 

defiant:

 class MyComp: public Compare { bool operator()(const Row *r1, const Row *r2) { ... } } cmp; ... obj->DoSort(cmp); 

The g ++ compiler on Linux complains that: "cannot select an object of type Compare because the type Compare has abstract virtual functions"

Even if I change Compare just virtual (not clean), std::sort() still calls the code Compare::operator() instead of MyComp::operator() .

The call to cmp (r1, r2) compiles and returns the correct result.

I have to do something wrong, or I do not understand. Please help me!

+4
source share
1 answer

std::sort (and other STL functions) accept comparators by value, so your object is copied, but the derivative part (including its vtbl) is "cut".

You can wrap your object in a proxy:

 class Proxy { private: Compare &cmp; public: Proxy(Compare &cmp) : cmp(cmp) {} bool operator()(const Row *r1, const Row *r2) { return cmp(r1, r2); } }; ... MyCompare cmp = MyCompare(); std::sort(x.begin(), x.end(), Proxy(cmp)); 
+8
source

All Articles