4
#include <iostream>
#include <string>
#include <algorithm>    
int main()
{
 std::string str1 = "good", str2 = "luck";
 swap(str1,str2); /*Line A*/
 int x = 5, y= 3;
 swap(x,y); /*Line B*/
}

If I comment Line B the code compiles(http://www.ideone.com/hbHwf) whereas commenting Line A the code fails to compile(http://www.ideone.com/odHka) and I get the following error:

error: ‘swap’ was not declared in this scope

Why don't I get any error in the first case?

Bill
  • 14,257
  • 4
  • 43
  • 55
justin4now
  • 43
  • 1
  • 3

4 Answers4

7

swap(str1, str2) works because of Argument dependent lookup

P.S: Pitfalls of ADL

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
4

You're not qualifying swap; it works when passing in std::string objects because of ADL, but as int does not reside in namespace std you must fully qualify the call:

std::swap(x, y);

or use a using declaration:

using std::swap;
swap(x, y);
ildjarn
  • 62,044
  • 9
  • 127
  • 211
2

strings are in the std:: namespace, so the compiler looks for swap() for strings there. ints are not, so it doesn't. You want:

std::swap(x,y);
1

In both cases you should be using std::swap() instead of swap().

karlphillip
  • 92,053
  • 36
  • 243
  • 426