我要创建交换函数,该函数可以将两种不同类型的变量作为参数。例如)
int a = 2;
double b = 1.1
swap(a,b)//wish a = 1.1, b = 2
template<typename T, typename U>
void swap(T& x, U& y)//it doesn't work due to automatic type cast
{
U temp = x;
x = y;
y = temp;
std::cout << "swap" << std::endl;
}
您不能这样做,因为不能更改对象类型。该double将被截断为int,该整数将被保存为double。但是,您可以使用std::variant
s,如下所示
#include <variant>
#include <iostream>
void swapDoubleVariantByIntOne(std::variant<int, double>& intVar, std::variant<int, double>& doubleVar)
{
auto temp = std::get<double>(doubleVar);
doubleVar = std::get<int>(intVar);
intVar = temp;
std::cout << "swap" << std::endl;
}
int main(){
std::variant<int, double> a = 2;
std::variant<int, double> b = 1.1;
swapDoubleVariantByIntOne(a, b);
std::cout << "a: " << std::get<double>(a)<< " b: " << std::get<int>(b) ;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句