C++ STL: Using derived virtual class as "Strict Weak Ordering" for std::sort()
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!
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));
精彩评论