0

クラス Stack の 2 つの異なる実装を作成したいと考えています。

(1)

template<typename element_type, typename container_type = std::vector<element_type> >
   class Stack{//...

    };

(2)

template<typename element_type, size_t container_size>
   class Stack{
   };

両方の実装を 1 つのファイルで定義すると、コンパイラ エラーが発生します。両方を同じファイルに入れることは可能ですか?

//compiler errors:

Stack.hpp:119:46: error: declaration of template ‘template<class element_type, long unsigned int container_size> int containers::Stack()’
Stack.hpp:25:9: error: conflicts with previous declaration ‘template<class element_type, class container_type> class containers::Stack’
Stack.hpp:25:9: error: previous non-function declaration ‘template<class element_type, class container_type> class containers::Stack’
Stack.hpp:119:46: error: conflicts with function declaration ‘template<class element_type, long unsigned int container_size> int containers::Stack()’
4

3 に答える 3

3

いいえ、できません。異なるテンプレート パラメーターを持つテンプレート化されたクラスの 2 つのバージョンを持つことはできません。この 2 種類を別の方法で呼び出すStackか、別の名前空間に配置することをお勧めします。

于 2012-05-28T20:08:38.233 に答える
2

次のように書く必要があります。

template<typename element_type, typename container_type = std::vector<element_type> >
class Stack {
  // This is *not* the specialization
};

template<typename element_type>
class Stack<element_type, std::vector<element_type> > {
  // Specialization goes here.
};

編集: テンプレート パラメーターの型を変更することはできません。

于 2012-05-28T20:09:02.713 に答える
1

パラメータの種類が異なる場合は、2 つの異なる名前を付ける必要があります。

于 2012-05-28T20:08:28.580 に答える