8

What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?

It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sense to favor one over the other?

The reason why I bring this up is because I have a templated container, where the containers themselves have a hierarchical relationship. I would like to write algorithms that use these containers without caring about which specific container it is. Also, some algorithms would benefit from knowing that the template type satisfied certain concepts (Comparable, for example).

So, on one hand, I want containers to behave polymorphicly. On the other, I still have to use concepts if I want to correctly implement some algorithms. What is a junior developer to do?

4

5 に答える 5

0

コンパイル時ポリモーフィズムと実行時ポリモーフィズムの違いの簡単な例として、次のコードを考えてみましょう。

template<typename tType>
struct compileTimePolymorphism
{ };

// compile time polymorphism,
// you can describe a behavior on some object type
// through the template, but you cannot interchange 
// the templates
compileTimePolymorphism<int> l_intTemplate;
compileTimePolymorphism<float> l_floatTemplate;
compileTimePolymorphism *l_templatePointer; // ???? impossible

struct A {};
struct B : public A{};
struct C : public A{};

// runtime polymorphism 
// you can interchange objects of different type
// by treating them like the parent
B l_B;
C l_C:
A *l_A = &l_B;
l_A = &l_C;

コンパイル時のポリモーフィズムは、あるオブジェクトの動作が他のオブジェクトに依存する場合に適したソリューションです。オブジェクトの動作を変更する必要がある場合は、ランタイム ポリモーフィズムが必要です。

この 2 つは、ポリモーフィックなテンプレートを定義することで組み合わせることができます。

template<typename tType>
struct myContainer : public tType
{};

問題は、コンテナの動作をどこで変更する必要があるか (ランタイム ポリモーフィズム)、コンテナに含まれるオブジェクトによって動作がどこに依存するか (コンパイル時ポリモーフィズム) です。

于 2009-03-07T02:26:10.597 に答える
0

コンパイル時に決定できる場合は、テンプレートを使用します。それ以外の場合は、継承と仮想関数を使用してください。

于 2009-03-06T23:57:38.080 に答える