我可以在不使用模板的情况下交换任意类型的两个实体 [英] Can I Swap Two Entities Of Arbitrary Type Without Using Templates
本文介绍了我可以在不使用模板的情况下交换任意类型的两个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题标题全部说明..
解决方案
在C ++ 11中,您可以使用auto关键字来声明临时变量,例如:
auto temp = a;
a = b;
b = temp;
适用于支持赋值运算符的所有类型和类。
数值支持exclusive-or运算符的类型可以使用以下技巧:
a = a ^ b;
b = a ^ b;
a = a ^ b;
有关说明,请参阅: http:// en。 wikipedia.org/wiki/XOR_swap_algorithm [ ^ ]
The Question Title Says It All .. .
解决方案
In C++11 you can use the auto keyword to declare the temporary variable, for example:
auto temp = a; a = b; b = temp;
That works for all types and classes that support the assignment operator.
For numeric types that support the exclusive-or operator you can use the following trick:
a = a ^ b; b = a ^ b; a = a ^ b;
For an explanation see: http://en.wikipedia.org/wiki/XOR_swap_algorithm[^]
这篇关于我可以在不使用模板的情况下交换任意类型的两个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文