【发布时间】:2014-07-31 16:49:45
【问题描述】:
使用静态变量和虚函数在 sort() 函数中实现谓词,用于多态类对象排序。这个解决方案有效吗?
下面的例子:
// 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);
我知道这可以通过使用非静态受保护成员来完成,但它需要为每个对象分配更多内存。
【问题讨论】:
-
你最好不要使用全部大写的标识符,除非你想花无数的时间来解决一些奇怪的错误
-
在需要常量时使用静态常量成员是完全可以的。 (按多态类型排序可能不太好,为什么需要它?)
-
这只是一个挑战,我想有一天我可能会遇到这样的问题。我对 OOP 还是很陌生,所以我什么都不知道。
-
您可以通过使用
type_index省去在每个类中编写GET_ID的麻烦——也就是说,如果您不需要类之间的特定相对顺序。