关于 boost::swap
的几个问题.请引用下面的代码,它基本上是来自 boost/swap.hpp
的剪切粘贴。 .我指的是库版本 1.43.0。
namespace boost_swap_impl
{
template<class T>
void swap_impl(T& left, T& right)
{
using namespace std;//use std::swap if argument dependent lookup fails
swap(left,right);
}
template<class T, std::size_t N>
void swap_impl(T (& left)[N], T (& right)[N])
{
for (std::size_t i = 0; i < N; ++i)
{
::boost_swap_impl::swap_impl(left[i], right[i]);
}
}
}
namespace boost
{
template<class T1, class T2>
void swap(T1& left, T2& right)
{
::boost_swap_impl::swap_impl(left, right);
}
}
- 为什么是
boost::swap
声明为template <typename T1, typename T2>
什么时候在其余代码中都处理相同的类型? - 如果我定义自己的全局函数
void swap(T&, T&)
我看到它是从swap_impl(T& left, T& right)
调用的全局函数.这是否不是冲突,因此不是自swap_impl
以来的错误条件?也使用namespace std
哪个已定义交换?
最佳答案
- 这使得它不像
std::swap
那样专门化,所以当std::swap
和boost::swap 都不会出现重载歧义错误
在范围内(std::swap
将优先)。 - 不,在重载决议期间非模板总是优先于模板,因此命名空间范围的非模板
swap
将优先于boost::swap
和std::swap
(就像为 UDT 重载的命名空间范围模板swap
一样——认为是部分特化的,但不是真的......)。请注意,与std::swap
不同,boost::swap
被显式编写以利用 ADL .
以下是 C++03 标准对这两点的看法 – [over.match.best] (§13.3.3/1):
Define ICSi(
F
) as follows:
- if
F
is a static member function, ICS1(F
) is defined such that ICS1(F
) is neither better nor worse than ICS1(G
) for any functionG
, and, symmetrically, ICS1(G
) is neither better nor worse than ICS1(F
); otherwise,- let ICSi(
F
) denote the implicit conversion sequence that converts the i-th argument in the list to the type of the i-th parameter of viable functionF
. 13.3.3.1 defines the implicit conversion sequences and 13.3.3.2 defines what it means for one implicit conversion sequence to be a better conversion sequence or worse conversion sequence than another.Given these definitions, a viable function
F1
is defined to be a better function than another viable functionF2
if for all arguments i, ICSi(F1
) is not a worse conversion sequence than ICSi(F2
), and then
- for some argument j, ICSj(
F1
) is a better conversion sequence than ICSj(F2
), or, if not that,F1
is a non-template function andF2
is a function template specialization, or, if not that,F1
andF2
are function template specializations, and the function template forF1
is more specialized than the template forF2
according to the partial ordering rules described in 14.5.5.2, or, if not that,- the context is an initialization by user-defined conversion (see 8.5, 13.3.1.5, and 13.3.1.6) and the standard conversion sequence from the return type of
F1
to the destination type (i.e., the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type ofF2
to the destination type.
关于c++ - 关于 boost::swap 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6115204/