假设我正在编写一些容器模板或其他东西。是时候为它专门化 std::swap
了。作为一个好公民,我将通过执行以下操作来启用 ADL:
template <typename T>
void swap(my_template<T>& x, my_template<T>& y) {
using std::swap;
swap(x.something_that_is_a_T, y.something_that_is_a_T);
}
这非常整洁。直到我想添加一个异常规范。只要 T
的交换是 noexcept
,我的 swap
就是 noexcept
。所以,我会写这样的东西:
template <typename T>
void swap(my_template<T>& x, my_template<T>& y)
noexcept(noexcept(swap(std::declval<T>(), std::declval<T>())))
问题是,里面的swap
必须是ADL发现的swap
或者std::swap
。我该如何处理?
最佳答案
我想我会把它移到一个单独的命名空间中
namespace tricks {
using std::swap;
template <typename T, typename U>
void swap(T &t, U &u) noexcept(noexcept(swap(t, u)));
}
template <typename T>
void swap(my_template<T>& x, my_template<T>& y)
noexcept(noexcept(tricks::swap(std::declval<T>(), std::declval<T>())))
{
using std::swap;
swap(x.something_that_is_a_T, y.something_that_is_a_T);
}
或者,您可以将整个代码移动到 tricks
并委托(delegate)给那里。
关于c++ - 如何编写启用 ADL 的尾随返回类型或 noexcept 规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7635939/