<分区>
Possible Duplicate:
How can I check whether multiple variables are equal to the same value?
有没有办法这样写:
if ((var1==var2) && (var2==var3) && (var3==var4) ...)
变成这样
if (var1==var2==var3==var4 ...)
?
标签 c++ if-statement
<分区>
Possible Duplicate:
How can I check whether multiple variables are equal to the same value?
有没有办法这样写:
if ((var1==var2) && (var2==var3) && (var3==var4) ...)
变成这样
if (var1==var2==var3==var4 ...)
?
最佳答案
在 C++11 中,您可以像这样编写一组函数:
template<typename T>
bool all_equal(T const &)
{
return true;
}
template<typename T, typename U, typename... Args>
bool all_equal(T const & a, U const & b, Args const&... c)
{
return a==b && all_equal(b,c...);
}
int main()
{
std::cout << all_equal(1,2,3) << '\n';
std::cout << all_equal(1,1,1) << '\n';
}
编辑:我猜 Steve Jessop 对链接拷贝有同样的想法 here
关于C++ - if 语句简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14143736/