c++ - 如何编写启用 ADL 的尾随返回类型或 noexcept 规范?

标签 c++ c++11 argument-dependent-lookup noexcept

假设我正在编写一些容器模板或其他东西。是时候为它专门化 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/

相关文章:

c++ - 通过 lambda 函数中的引用/值捕获成本?

c++ - 为什么这个函数调用没有拒绝不合适的重载?

c++ - ADL 在特定情况下不起作用

c++ - scanf不接受输入

c++ - 我如何优化这个 dijkstra 结构代码?

c++ - 如何获取指向重载未知的重载函数的任何重载的指针?

c++ - std::list 提示缺少第二个模板参数(分配器)

c++ - 从 MySQL 选择 LONGTEXT 列时 CRecordset 出现 "out of memory"异常

c++ - std::enable_if 有条件地编译一个成员函数

c++ - initializer_list 和参数相关的查找