2016-08-15 4 views
1

最後のパラメータではない場合、バリアブルテンプレート関数でパラメータパックがどのように機能するかを理解しようとしています。私のサンプルコードで私の呼び出しのいくつかがうまくいかない理由は分かりません。質問はコメントに記載されています。彼らは動作するか、私は何かを理解していないか、またはVS2015アップデート3のコンパイラはまだそれらをサポートしていませんか?関数テンプレートでは、パラメータパックの種類は、それが中にいた場合にのみ推定することができ、ので最後のパラメータパックコンパイルエラー

template <typename T> 
double sum(T t) { 
    return t; 
} 

template <typename T, typename... Rest> 
double sum(Rest... rest, T t) { 
    return t + sum(rest...); 
} 

template <typename T> 
double sum2(T t) { 
    return t; 
} 

template <typename T, typename... Rest> 
double sum2(T t, Rest... rest) { 
    return t + sum2(rest...); 
} 

template<typename... Args> 
void func(Args..., int = 0) 
{} 

void func() 
{ 
    func<int, int, int>(1, 1, 1); 
    func(1, 1, 1); // why doesn't this compile? 
    sum(1, 1); // why doesn't this compile? 
    sum<int, int>(1, 1); 
    sum<int, int, int>(1, 1, 1); // why doesn't this compile while func<int, int, int>(1, 1, 1) does? 

    // why are these compile? I only changed the order of the parameters compared to sum() 
    sum2(1); 
    sum2(1, 1); 
    sum2(1, 1, 1); 
} 

答えて

2

私は限り私が知っている、本当に専門家ではないんだけど...

func(1, 1, 1); // why doesn't this compile? 

最後の位置。

最初の呼び出し

func<int, int, int>(1, 1, 1); 

作品パラメータの種類が推定されていないが、説明されているので(Args...int, int, intある)とfunc()(デフォルト値ゼロを有する)第intを受信

電話

func<int, int>(1, 1, 1); 

Args...int, intとして説明するとfunc()機能がデフォルト値と第intを受ける1


sum(1, 1); // why doesn't this compile? 

同じ理由:パラメータパックはそう推測することができない最後の位置にありません。しかしTintともintとしてRest...としてexplicatedされているため

sum<int, int>(1, 1); 

動作します。 Tint, intとしてintRest...としてexplicatedているので


sum<int, int, int>(1, 1, 1); // why doesn't this compile while func<int, int, int>(1, 1, 1) does? 

拳レベルの呼び出しが動作します。 sum<int, int, int>(1, 1, 1)sum(rest...)と呼びます。この場合、sum(1, 1)です。それはRest...を推定

// why are these compile? I only changed the order of the parameters compared to sum() 
sum2(1); 
sum2(1, 1); 
sum2(1, 1, 1); 

sum2()Rest...が最後の位置にあるパラメータパックのリストがそうである可能性があるため


を推定することはできませんので、最後の位置にありません(とある)ので、失敗している sum(1, 1)です。