samedi 6 juin 2020

C++: How to keep common code path for multiple overloaded functions?

Does anyone know how I can keep the code in swap_1() and swap_2() common? I'm a bit confused how to do that because the referencing of the argument types are different.

// overload the function call
template<class T> void swap_1(T&& a, T& b)
{
    T tmp {move(a)};
    a = move(b);
    b = move(tmp); 
}

template<class T> void swap_1(T& a, T&& b)
{
    T tmp {move(a)};
    a = move(b);
    b = move(tmp); 
}

void f1()
{
    vector<int> v = {1, 2, 3};

    swap_1(v, vector<int>{4, 5, 6});
}

Aucun commentaire:

Enregistrer un commentaire