gpt4 book ai didi

c++ - 关于 boost::swap 的问题

转载 作者:IT老高 更新时间:2023-10-28 22:36:54 25 4
gpt4 key购买 nike

关于 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);
}
}
  1. 为什么是 boost::swap声明为 template <typename T1, typename T2>什么时候在其余代码中都处理相同的类型?
  2. 如果我定义自己的全局函数 void swap(T&, T&)我看到它是从 swap_impl(T& left, T& right) 调用的全局函数.这是否不是冲突,因此不是自 swap_impl 以来的错误条件?也使用 namespace std哪个已定义交换?

最佳答案

  1. 这使得它不像 std::swap 那样专门化,所以当 std::swapboost::swap 都不会出现重载歧义错误 在范围内(std::swap 将优先)。
  2. 不,在重载决议期间非模板总是优先于模板,因此命名空间范围的非模板 swap 将优先于 boost::swapstd::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 function G, 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 function F. 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 function F2 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 and F2 is a function template specialization, or, if not that,
  • F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 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 of F2 to the destination type.

关于c++ - 关于 boost::swap 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6115204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com