0

アプリケーションに一般的な問題があります。パフォーマンスを向上させるために、作成したArrayクラスで遅延初期化を使用したいと思います。すべてのコードが単一の*.hファイルにある場合はすべて正常に機能しますが、コードを* .h * .cppファイルに分割すると、コンパイラーはリンカーエラーを返します。ヘッダーファイルには、

template <class T>
class simpleArray { ... some methods\operators declarations. ... }

template <typename T, typename derType=simpleArray<T>>
class myArray{.... some methods\operators declarations. ... }

そして私は次の明示的な宣言をしました:

template class myArray<double>; 
template class myArray<int>;
template class simpleArray<double>; 
template class simpleArray<int>;

* .cppファイルには、メソッドと演算子の実装があります。特に、2つの割り当て演算子があります。

template <class T, class derType>   
myArray<T,derType>& myArray<T,derType>::operator= (myArray<T,derType> const& right)
    {... some code ...}

template<class T, class derType>
template <class T2, class R2>   
    myArray<T,derType>& myArray<T,derType>::operator= (myArray<T2,R2> const& right) 
    { ... some code ...}

最初のものは正常に動作し、2番目のもの(Arra = Array)は次のエラーを返します。

 Error  70  error LNK1120: 1 unresolved externals   
 Error  69  error LNK2019: unresolved external symbol "public: class myArray <double,class simpleArray<double> > & __thiscall myArray <double,class simpleArray<double> >::operator=<int,class simpleArray<int> >(class myArray <int,class simpleArray<int> > const &)" 

いくつかの解決策を提案してもらえますか?すべてのコードを同じファイルに含める必要がありますか?はっきりしているといいのですが。サポートしてくれてありがとう!

追伸 テンプレートを使用する場合のコード編成に関する「ベストプラクティス」ドキュメントはありますか?

4

1 に答える 1

1

operator=テンプレート定義を.cppファイルに配置したために発生した問題:

template <class T, class derType>
template <class T2, class R2>
myArray<T,derType>& myArray<T,derType>::operator=(myArray<T2,R2> const& right)
{ ... }

使用している明示的なインスタンス化は、テンプレートクラスの通常の関数メンバーでは正常に機能しますが、テンプレートクラスのテンプレート関数メンバーでは機能しません。明示的なインスタンス化ディレクティブでは、クラステンプレートパラメーターであり、関数テンプレートパラメーターではない実際の型と型Tのみを指定するからです。derTypeT2R2

可能な解決策:

  1. テンプレートoperator=定義をに移動して.h、コンパイラが呼び出し場所でそれをインスタンス化できるようにします
  2. /と/operator=のすべての可能な組み合わせを使用して、テンプレートの明示的なインスタンス化を提供します。TderTypeT2R2

サンプル:

 // Explicit instantiation of template classes
 template class myArray<double>;
 template class myArray<int>;
 template class simpleArray<double>;
 template class simpleArray<int>; 

 // Explicit instantiation of template members
 template myArray<double>& myArray<double>::operator=(myArray<int> const&);
 template myArray<int>& myArray<int>::operator=(myArray<double> const&);

PS最高のテンプレートガイドはまだC++テンプレートです。DavidVandevoordeとNicolaiM.Josuttisによる完全ガイド。新しいC++11機能についてはまだ説明していませんが、基本的なトピックと最も高度なトピックはまだ実際のものです。

于 2012-10-13T22:46:39.367 に答える