Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL: Using derived virtual class as "Strict Weak Ordering" for std::sort()

Tags:

c++

sorting

stl

I hit a wall using std::sort(). I have a pure virtual class (named Compare) that the caller of a method derives from (named MyComp). I use the pure virtual class for my API's prototype:

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

the caller:

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

The g++ compiler on Linux complains that: "cannot allocate an object of type 'Compare' since type 'Compare' has abstract virtual functions"

Even if I modify Compare to be simply virtual (not pure), the std::sort() still calls the Compare::operator() code instead of the MyComp::operator().

Calling cmp(r1,r2) compiles fine and return the right result.

I must do something wrong, or I do not get it. Help please!

like image 296
0x6adb015 Avatar asked Jan 19 '23 20:01

0x6adb015


1 Answers

std::sort (and other STL functions) take comparator objects by value, so your object is being copied, but the derived part (including its vtbl) is being "sliced away".

You could 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));
like image 152
Oliver Charlesworth Avatar answered Jan 30 '23 08:01

Oliver Charlesworth