2つのパラメータt1とt2を使用する次の例があります。2つ以上のパラメータを持つバリデリックテンプレート関数
template<typename T>
bool Compare(T t1, T t2)
{
return t1 == t2;
}
template<typename T, typename... Args>
bool Compare(T t1, T t2, Args... args)
{
return (t1 == t2) && Compare(args...);
}
int main(void)
{
Compare(1, 1, "string", "string");
}
機能比較は、同じタイプであり比較可能なパラメータのペアを取ります。 2つのペアが比較され、最後の2つのパラメータに達するまで、パラメータパックが再帰的に渡されます。 再帰を停止するには、パラメータパックなしでCompare関数の実装を使用します。私は関数は比較に第3引数T3を追加したいと思います
は次のようにする必要があります:
template<typename T>
bool Compare(T t1, T t2, T t3)
{
return t1 == t2 == t3;
}
template<typename T, typename... Args>
bool Compare(T t1, T t2, T t3, Args... args)
{
return (t1 == t2 == t3) && Compare(args...);
}
int main(void)
{
Compare(1, 1, 1, "string", "string", "string");
}
私は、この関数は、次の3を再帰的に処理されている比較に3つのパラメータを取ることを期待しています。私はこのコードをコンパイルしようとする 私は次のエラーを取得:同じ種類の3つのパラメータセットを比較するために、この機能を実装する方法を
>xxx\source.cpp(4): error C2446: '==': no conversion from 'const char *' to 'int'
1> xxx\source.cpp(4): note: There is no context in which this conversion is possible
1> xxx\source.cpp(10): note: see reference to function template instantiation 'bool Compare<const char*>(T,T,T)' being compiled
1> with
1> [
1> T=const char *
1> ]
1> xxx\source.cpp(15): note: see reference to function template instantiation 'bool Compare<int,const char*,const char*,const char*>(T,T,T,const char *,const char *,const char *)' being compiled
1> with
1> [
1> T=int
1> ]
1>xxx\source.cpp(4): error C2040: '==': 'int' differs in levels of indirection from 'const char *'
? t1
、t2
とt3
が全て等しいかどうかをチェックしない
最後の行を展開するには: "string"を含むstd文字列のc_str()を引数の1つとして渡すと、すべての文字列が "string" 。可能であれば、std文字列(その中に文字列定数をラップする文字列も含む)を使用するほうがよいでしょう。 –