C++ how can I make a swap function between two variables which are different in type

597 views Asked by At

I want to make swap function, which can take two different type of variables as parameters. for example)

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;
    }
2

There are 2 answers

0
asmmo On BEST ANSWER

You cannot do that because the objects types can't be changed. the double will be truncated as an int and the integer will be saved as a double. However, you can use std::variants, as follows

#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) ;

}

Demo

0
ikh On

You cannot. Since the type of a is int, it cannot hold values like 1.1. Unlike dynamic typed language like javascript, In static typed language like C++, the type of a variable cannot be changed.