msk*_*msk 7 c++ recursion variadic-templates
我有以下示例,其中使用了两个参数t1和t2.
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");
}
Run Code Online (Sandbox Code Playgroud)
函数比较采用相同类型且可以比较的参数对.比较两对,然后递归地传递参数包,直到达到最后两个参数.为了停止递归,我使用了不带参数包的比较函数的实现.
我想添加第三个参数t3所以函数Compare应该是这样的:
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");
}
Run Code Online (Sandbox Code Playgroud)
我希望这个函数需要三个参数进行比较,然后接下来的三个参数被递归处理.当我尝试编译此代码时,我获得以下错误:
>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 *'
Run Code Online (Sandbox Code Playgroud)
如何实现此功能来比较同一类型的三个参数集?
t1 == t2 == t3
Run Code Online (Sandbox Code Playgroud)
这并不检查t1,t2并且t3都是平等的,它会检查是否t1平等t2,然后检查是否由此而来bool等于t3.
也许你想要的是(假设合理的相等运算符):
t1 == t2 && t1 == t3
Run Code Online (Sandbox Code Playgroud)
所以你的代码看起来像这样:
template<typename T>
bool Compare(T t1, T t2, T t3)
{
return t1 == t2 && t1 == t3;
}
template<typename T, typename... Args>
bool Compare(T t1, T t2, T t3, Args... args)
{
return t1 == t2 && t1 == t3 && Compare(args...);
}
Run Code Online (Sandbox Code Playgroud)
请注意,使用字符串文字进行的测试调用会进行指针比较,这可能不是您想要的.