これは、私が達成しようとしていることを説明するサンプルコードです。
基本的に、クラスで利用可能ないくつかの基本的な操作に依存するアルゴリズムがあります。これらの操作は、純粋な抽象基本クラスで定義しました。特定のオブジェクトのクラスを派生させることにより、そのアルゴリズムをさまざまなオブジェクトに適用して、それらの操作を提供したいと考えています。
ただし、これらの操作に関する限り、異なる派生オブジェクトは互いに互換性がありません。私の質問は、RTTI の使用を避けて、たとえば、ブール派生 2::同一 (const base* other2)、アサート (または他の終了メカニズム) で、other2 が派生 2 型ではないことを確認できるかどうかです。
1 つの代替手段は、特定の派生オブジェクトで関数アルゴリズムをテンプレート化することですが、それは実装がヘッダー ファイルに存在する必要があることを意味します。これは、1) テスト目的でアルゴリズム コードを変更すると、コードの大部分の再コンパイル 2) アルゴリズムの実装は、エンドユーザーから隠されているソース ファイルに適切に存在するのではなく、ヘッダーで公開されます。
ヘッダーファイル
#include <list>
class base
{
public:
virtual float difference(const base*) const = 0;
virtual bool identical(const base*) const = 0;
};
class derived1 : public base
{
public:
float difference(const base* other1) const
{
// other1 has to be of type derived1
if(typeid(other1) == typeid(this))
{
// process ...
}
else
{
assert(0);
}
return 1;
}
bool identical(const base* other1) const
{
// other1 has to be of type derived1
if(typeid(other1) == typeid(this))
{
// compare...
}
else
{
assert(0);
}
return true;
}
};
class derived2 : public base
{
public:
float difference(const base* other2) const
{
// process ...
// other2 has to be of type derived2
return 2;
}
bool identical(const base* other2) const
{
// do comparison
// derived1 and derived2 cannot be compared
return true;
}
};
// Declaration
int algorithm(std::list<base*>& members);
アルゴリズムの実装 ソースファイル
#include "header_file_containing_base"
int algorithm(std::list<base*>& members)
{
// This function only relies on the interface defined in base
// process members;
return 1;
}
メインプログラム
int main()
{
// Create lists of derived1 and derived2
// Run algorithm on these lists
}