【发布时间】:2016-06-30 13:55:57
【问题描述】:
我有以下示例,其中使用了两个参数 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");
}
Function Compare 接受相同类型且可以比较的成对参数。 比较两对,然后递归传递参数包,直到达到最后两个参数。 为了停止递归,我使用了不带参数包的比较函数的实现。
我想添加第三个参数 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");
}
我希望这个函数需要三个参数进行比较,然后递归处理接下来的三个。 当我尝试编译此代码时,我收到以下错误:
>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 *'
如何实现这个函数来比较相同类型的三个参数的集合?
【问题讨论】:
标签: c++ recursion variadic-templates