Is this C++ template declaration genuinely incorrect or is my compiler mucking up? -


edit: thank answers! said, code provided class, namespace , name of function included. i'm glad understand namespace std entails though, , i've included inputs comments within answer (though answer remains unchanged).

the code below includes piece created. class, only part need judged. compiler isn't running (ambiguous calls overloaded function) feel correct.

template <class data_type> void swap(data_type &a, data_type &b) //swaps 2 variables {    data_type c; //temp variable    c = a;    = b;    b = c; } 

here full code:

#include <iostream> #include <string>  using namespace std;  template <class data_type> void swap(data_type &a, data_type &b) //swaps variables {    data_type c;    c = a;    = b;    b = c; }  int main( ) {     string x = "first", y = "second";     int m = 10, n = 20;     char q = 'q', r = 'r';      cout<<"x before swap called = "<<x<<" , y before swap called = " <<y<<endl;     swap(x,y);     cout<<"x after swap called = "<<x<<" , y after swap called = " <<y<<endl<<endl;      cout<<"m before swap called = "<<m<<" , n before swap called = " <<n<<endl;     swap(m,n);     cout<<"m after swap called = "<<m<<" , n after swap called = " <<n<<endl<<endl;      cout<<"q before swap called = "<<q<<" , r before swap called = "   <<r<<endl;     swap(q,r);     cout<<"q after swap called = "<<q<<" , r after swap called = "    <<r<<endl<<endl;      return 0; } 

the standard library comes template std::swap (see cpp reference), , defining own swap-template function. far no problem, once declare using namespace std, use of swap ambiguous, since compiler cannot decide whether take std::swap or own swap.

so, mentioned others, avoid using namespace std statement.

additionally, think of declaring "your" swap in own namespace, like:

namespace class1_exercise {      template <class data_type>     void swap(data_type &a, data_type &b) //swaps variables     {         data_type c;         c = a;         = b;         b = c;     } } 

thereby, can make distinction between "your" swap , std::swap more explicit:

std::swap(x,y); // versus: class1_exercise::swap(x,y); 

Comments