调用重载' swap(char&,char&)'很暧昧

时间:2015-04-25 02:15:41

标签: c++

我无法弄清楚下面swap(arr[i++],arr[n--]);的含糊不清。请教我不正当的方法。

#include <iostream>
#include <string>

template <typename T> void swap ( T & a, T & b )
{
    T temp = b;
    b = a;
    a = temp;
}

template <typename T> void reverse_array ( T * arr, size_t n )
{
   size_t i = 0;
   while (i < n) swap(arr[i++],arr[n--]); // problem line
}


int main () 
{
   char mystr [] = "Obama smokes";
   reverse_array(mystr, sizeof(mystr)/sizeof(char));
   return 0;
}

2 个答案:

答案 0 :(得分:7)

codepad has an implicit using namespace std;,这是一个非常糟糕的主意,会导致swapstd::swap发生冲突。您可以使用::swap代替sizeof mystr - 2,而不是sizeof(mystr)/sizeof(char),而不是{{1}}。

答案 1 :(得分:0)

正如@minitech在他的回答中提到的,问题是由于隐式名称空间声明,例如using namespace std;

由此我收到以下错误,表明冲突是std::swap

    100%] Building CXX object CMakeFiles/csi_projects.dir/main.cpp.o
    /home/vsnyc/ClionProjects/main.cpp: In instantiation of ‘void reverse_array(T*, size_t) [with T = char; size_t = long unsigned int]’:
    /home/vsnyc/ClionProjects/main.cpp:151:52:   required from here
    /home/vsnyc/ClionProjects/main.cpp:144:43: error: call of overloaded ‘swap(char&, char&)’ is ambiguous
         while (i < n) { swap(arr[i++],arr[n--]); } // problem line
                                               ^
    /home/vsnyc/ClionProjects/main.cpp:144:43: note: candidates are:
    /home/vsnyc/ClionProjects/main.cpp:134:28: note: void swap(T&, T&) [with T = char]
     template <typename T> void swap ( T & a, T & b )
                                ^
    In file included from /usr/include/c++/4.8/bits/stl_pair.h:59:0,
                     from /usr/include/c++/4.8/bits/stl_algobase.h:64,
                     from /usr/include/c++/4.8/bits/char_traits.h:39,
                     from /usr/include/c++/4.8/ios:40,
                     from /usr/include/c++/4.8/ostream:38,
                     from /usr/include/c++/4.8/iostream:39,
                     from /home/vsnyc/ClionProjects/main.cpp:1:
    /usr/include/c++/4.8/bits/move.h:166:5: note: void std::swap(_Tp&, _Tp&) [with _Tp = char]
         swap(_Tp& __a, _Tp& __b)
         ^