简体   繁体   English

C++ STL:使用派生的虚拟 class 作为 std::sort() 的“严格弱排序”

[英]C++ STL: Using derived virtual class as “Strict Weak Ordering” for std::sort()

I hit a wall using std::sort().我使用 std::sort() 撞墙了。 I have a pure virtual class (named Compare ) that the caller of a method derives from (named MyComp ).我有一个纯虚拟 class (名为Compare ),方法的调用者来自(名为MyComp )。 I use the pure virtual class for my API's prototype:我将纯虚拟 class 用于我的 API 原型:

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" Linux 上的 g++ 编译器抱怨说:“无法分配类型为 'Compare' 的 object,因为类型 'Compare' 具有抽象虚函数”

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() .即使我将Compare修改为简单的虚拟(不是纯), std::sort()仍然调用Compare::operator()代码而不是MyComp::operator()

Calling cmp(r1,r2) compiles fine and return the right result.调用 cmp(r1,r2) 可以很好地编译并返回正确的结果。

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". std::sort (和其他 STL 函数)按值获取比较器对象,因此您的 object 正在被复制,但派生部分(包括其 vtbl)被“切掉”。

You could wrap your object in a proxy:您可以将 object 包装在代理中:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM