テンプレートメソッドを定義するときに戻り値型にテンプレート引数が必要だが、引数型ではない理由が分かっていますか?例:メソッド定義中の戻り型でテンプレート引数が必要
template<typename T>
struct Car {
Car drive(Car); // will be defined after the template declaration.
};
// Attempt #1: does not compile.
// Error: use of class template Car requires template arguments
template<typename T>
inline Car Car<T>::drive(Car) {}
// Attempt #2: compiles!
// The only difference is the use of template argument in return type.
// However, note that the argument to func does not require template argument!
template<typename T>
inline Car<T> Car<T>::drive(Car) {}
テンプレート引数は、戻り値型のために必要なものの、引数型のために必要とされていない理由はわかりません。試み#1が失敗したとき、私はあまりにも失敗する試み#2を期待していたと私は必要があるだろうと予想:
template<typename T>
inline Car<T> Car<T>::drive(Car<T>) {} // but no need to go this far.
が、2位に働いを試み!
この現象が発生する理由はありますか?
これは、左から右に解析するためだと思います。 'template typename T>の後、テンプレートタイプがまだわかりません。インラインカーではまだ何らかの関数を宣言している可能性があるので、 'Car'は有効ではないので' Car 'を明確にする必要があります。 'Car :: ...'の後、あなたは 'struct car 'のコンテキスト内にあり、引数 'Car'は暗黙的に' Car 'です。 –