简体   繁体   English

为什么将 boost::swap 中的 swap_impl 移动到单独的命名空间?

[英]why move swap_impl in boost::swap to a separate namespace?

I am looking into boost::swap implementation:我正在研究 boost::swap 实现:

namespace boost_swap_impl
{
  template<class T>
  BOOST_GPU_ENABLED
  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>
  BOOST_GPU_ENABLED
  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>
  BOOST_GPU_ENABLED
  void swap(T1& left, T2& right)
  {
    ::boost_swap_impl::swap_impl(left, right);
  }
}

The implementation also contains the following comment:该实现还包含以下注释:

// Note: the implementation of this utility contains various workarounds:
// - swap_impl is put outside the boost namespace, to avoid infinite
// recursion (causing stack overflow) when swapping objects of a primitive
// type.

However, I don't understand why primitive types (and why only primitive) cause infinite recursion.但是,我不明白为什么原始类型(以及为什么只有原始类型)会导致无限递归。

If swap_impl is in the namespace boost , the call swap(left,right);如果swap_impl在命名空间boost ,则调用swap(left,right); in the implementation of swap_impl will resolve to boost::swap instead of std::swap .swap_impl的实现中,将解析为boost::swap而不是std::swap That is, boost::swap -> boost::swap_impl -> boost::swap , and thus infinite recursion.也就是说, boost::swap -> boost::swap_impl -> boost::swap ,因此是无限递归。

As dyp has pointed out in the comment, the correct interpretation of the comment //use std::swap if argument dependent lookup fails should be as follows: An unqualified swap(left,right) is intended to select a specialized swapping function for the two arguments, found in the namespace of the types of those arguments.正如 dyp 在评论中指出的那样, //use std::swap if argument dependent lookup fails ,则注释//use std::swap if argument dependent lookup fails的正确解释应如下所示: 未限定的swap(left,right)旨在为两个参数,在这些参数类型的命名空间中找到。 If such a specialized function has not been provided, the generic std::swap is used as a fallback.如果没有提供这样的专用函数,则使用通用std::swap作为后备。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM