C++ 类中用于实现sort()谓词的静态变量和虚函数

C++ 类中用于实现sort()谓词的静态变量和虚函数,c++,sorting,object,static,C++,Sorting,Object,Static,使用静态变量和虚函数在用于多态类对象排序的排序函数中实现谓词。这个解决方案有效吗 示例如下: // Here we've got virtual function that return a static variable // and each derived class has a separate unique static class Base { protected: virtual const int &GET_ID const { return B

使用静态变量和虚函数在用于多态类对象排序的排序函数中实现谓词。这个解决方案有效吗

示例如下:

// Here we've got virtual function that return a static variable
// and each derived class has a separate unique static

class Base {
    protected:
        virtual const int &GET_ID const { return BASE_ID; }
    private:
        static const int BASE_ID = 0;
}

class Derived : public Base {
    private:
        const int &GET_ID const { return DERIVED_ID; }
        static const int DERIVED_ID = 1;
}

class Derived2 : public Base {
    private:
        const int &GET_ID const { return DERIVED2_ID; }
        static const int DERIVED2_ID = 2;
}


// We can then construct a predicate for the sort function to
// sort a list of polymorphic object

bool compare (Base *base1, Base *base2) {
    return base1->GET_ID() < base2->GET_ID();
} 

std::sort(containerOfBasePtr.begin(), containerOfBasePtr.end(), compare);

我知道这可以通过使用非静态受保护的成员来实现,但它需要为每个对象分配更多的内存。

效率是一个相对术语。但是如果您不希望有任何额外的内存使用,那么使用虚拟函数或type_索引是我能想到的唯一选项


另一方面,如果我们更多地了解问题的背景,也许可以用一种完全不同的方式来解决这个问题。一种可能的替代方法是将不同的对象存储在完全不同的容器中,由无序的映射索引。

最好不要使用所有大写标识符,除非你想在某些奇怪的错误上花费无休止的时间。当你需要常量时,使用静态常量成员是完全可以的。按多态类型排序可能不是个好主意,为什么需要它?这只是一个挑战,我想有一天我可能会遇到这样的问题。我对OOP还是一个新手,所以我什么都不知道。如果不需要在类之间进行特定的相对排序,您可以通过使用来避免在每个类中编写GET_ID的麻烦。