2 つの属性 x と y を持つクラス名 Default があるとします。
オブジェクトを比較するデフォルトの操作は、属性 x を使用することです。
このオブジェクトを他の属性 y を使用して比較したい場合、
1. 属性 y を使用して比較できる新しい派生クラスを作成し、Default からその新しいクラスにポインターをキャストしてオブジェクトを比較しても安全ですか?
2. 操作のパフォーマンスを低下させずにこれを行う代替方法は何ですか?
要件は、ソート アルゴリズムのシグネチャを変更して関数ポインターを差分コンパレーターに渡すことができないことです。
ちなみにこの方法は、データの変換やコピーに費用はかかりません。
class Default {public:int x; int y;};
class Compare1 : public Default {};
bool operator < (const Default &left,const Default &right)
{
return left.x < right.x;
}
bool operator < (const Compare1 &left,const Compare1 &right)
{
return left.y < right.y;
}
template<typename T>
int *sort_element(const T *data, int size)
{
int *permute;
//... do some sorting by using < comparator ...
return permute;
}
int main(){
Default *obj;
int obj_size;
//… initialize obj and obj size..
// sorting object with default order.
int *output_default = sort_element(obj, obj_size)
// sorting with customize comparator.
Compare1 *custom1 = static_cast<Compare1*>(obj);
int *output_custom1 = sort_element(custom1, obj_size);
}