有谁知道我如何保持代码swap_1()
和swap_2()
通用? 我有点困惑如何做到这一点,因为参数类型的引用是不同的。
// 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});
}
您可以创建第三个模板并从其他模板调用它:
template<class T, class U>
void swap(T&& a, U&& b)
{
typename std::remove_reference<T>::type tmp {std::move(a)};
a = std::move(b);
b = std::move(tmp);
}
// overload the function call
template<class T>
void swap_1(T&& a, T& b)
{
swap(std::forward<T>(a), b);
}
template<class T>
void swap_1(T& a, T&& b)
{
swap(a, std::forward<T>(b));
}
请记住,T &&a
是通用引用,而不是 R 值引用。您甚至可以将这两个函数替换为
template<class T, class U, class = typename std::enable_if<std::is_same<typename std::remove_reference<T>::type, typename std::remove_reference<U>::type>::value>::type>
void swap_1(T&& a, U&& b)
{
typename std::remove_reference<T>::type tmp {std::move(a)};
a = std::move(b);
b = std::move(tmp);
}
您用 C++11 标记了问题。使用较新版本的C++您可以编写更简单一些。这是一个较短的 C++14 版本:
template<class T, class U, class = std::enable_if_t<std::is_same<std::remove_reference_t<T>, std::remove_reference_t<U>>::value>>
void swap_1(T&& a, U&& b)
{
std::remove_reference_t<T> tmp {std::move(a)};
a = std::move(b);
b = std::move(tmp);
}