6

可変個引数テンプレート関数での構造体の回避に示されているソリューションを必要に応じて適応させようとしています。しかし、G++ の動作がわかりません。次の関数を検討してください。

 template <typename T, unsigned Size>
 int nextline(const typename std::array<T, Size> ar) {
    return 0;
 }

その後、コール

 nextline(std::array<int, 2> { 1,0 });

と不平を言うGCCと一致しません

eslong.cpp: In function ‘int main()’:
eslong.cpp:10:38: error: no matching function for call to ‘nextline(std::array<int, 2ul>)’
   nextline(std::array<int, 2> { 1,0 });
                                      ^
eslong.cpp:10:38: note: candidate is:
eslong.cpp:4:5: note: template<class T, unsigned int Size> int nextline(std::array<T, Size>)
 int nextline(const typename std::array<T, Size> ar) {
     ^
eslong.cpp:4:5: note:   template argument deduction/substitution failed:
eslong.cpp:10:38: note:   mismatched types ‘unsigned int’ and ‘#‘integer_cst’ not supported by dump_type#<type error>’
   nextline(std::array<int, 2> { 1,0 });
                                      ^
eslong.cpp:10:38: note:   ‘std::array<int, 2ul>’ is not derived from ‘std::array<T, Size>’

ただし、 orに変更unsigned Sizeすると一致します。ここで何が起こっているのかよくわかりません。への呼び出しのパラメーターが に変換されていませんか?unsigned long Sizesize_tSizestd::array<T, Size>size_t

4

2 に答える 2

10

std::array次のようにテンプレート化されています。

template<class T, std::size_t N > struct array;

sizeNは type である必要がありますsize_t。しかし、関数では、として解釈できない符号なし (int) を渡していますsize_tSFINAEによると、テンプレートを推測できない場合、テンプレートは存在しないため、テンプレート化された関数は存在しません。

呼び出し行の問題ではなく、関数テンプレートの宣言です。これを修正するには、正しいタイプを使用します。

template <typename T, size_t Size>
int nextline(const typename std::array<T, Size> ar) {
  return 0;
 }

この場合、あなたも使用します:

nextline(std::array<int, 2ul> { 1,0 });

推定してキャストできるため、引き続き機能します。


dypによる追加説明:

[temp.deduct.type]/17は、推定されたもの (テンプレート引数) の型が、推定されるテンプレート パラメーターと同じ型である必要がある非型テンプレート パラメーター用です。

于 2014-02-12T22:36:37.590 に答える