Why move swap_impl in boost :: swap to a separate namespace?

I look in 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 do not understand why primitive types (and why only primitive types) cause infinite recursion.

+2
c ++ boost argument-dependent-lookup
source share
1 answer

If swap_impl is in the boost namespace, call swap(left,right); in the implementation, swap_impl will be used instead of boost::swap instead of std::swap . That is, boost::swap -> boost::swap_impl -> boost::swap and therefore infinite recursion.

As dyp points out in the comment, the correct interpretation of the comment //use std::swap if argument dependent lookup fails should be as follows: unskilled swap(left,right) designed to select a specialized replacement function for the two arguments found in the namespace types of these arguments. If such a specialized function has not been provided, the generic std::swap used as a fallback.

+2
source share

All Articles