如何编写一个启用ADL的结尾返回类型或noexcept规范? [英] How do I write an ADL-enabled trailing return type, or noexcept specification?

查看:152
本文介绍了如何编写一个启用ADL的结尾返回类型或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 的交换,我的 swap 就是 noexcept 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

解决方案

我想我会把它移动到一个单独的命名空间

 命名空间技巧{
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);
}

或者,您可以将整个代码移动到 并委派到那里。


Imagine I'm writing some container template or something. And the time comes to specialize std::swap for it. As a good citizen, I'll enable ADL by doing something like this:

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

This is very neat and all. Until I want to add an exception specification. My swap is noexcept as long as the swap for T is noexcept. So, I'd be writing something like:

template <typename T>
void swap(my_template<T>& x, my_template<T>& y)
    noexcept(noexcept(swap(std::declval<T>(), std::declval<T>())))

Problem is, the swap in there needs to be the ADL-discovered swap or std::swap. How do I handle this?

解决方案

I think I would move it into a separate namespace

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

Alternatively you can move the whole code up into tricks and delegate to there.

这篇关于如何编写一个启用ADL的结尾返回类型或noexcept规范?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆