如何编写一个启用ADL的结尾返回类型或noexcept规范? [英] How do I write an ADL-enabled trailing return type, or noexcept specification?
问题描述
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屋!