0

The code given below is related to a template concept in c++. I am not getting a proper result while passing the variables. My expected output is swapped numbers. However, the compiler is showing an error.

#include<iostream>

using namespace std;

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

int main()
{
    int a1,b1;
    cin>>a1>>b1;
    swap(a1,b1);
    cout<<a1<<endl<<b1<<endl;
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • 3
    What error message are you seeing? Is it because your `swap` is ambiguous with [`std::swap`](http://en.cppreference.com/w/cpp/algorithm/swap)? Get rid of [`using namespace std;`](http://stackoverflow.com/q/1452721/241631) – Praetorian Oct 26 '15 at 15:58
  • 1
    And I keep saying this over and over and over again. NEVER write `using namespace std`. Thou shall not do this! – SergeyA Oct 26 '15 at 16:36

1 Answers1

0

get rid of 'using namespace std;' because in std namespace swap function template is already defined.

another solution you can specialize swap. But you can only specialize standard functions for user defined types

    #include<iostream>

    using namespace std;
    struct Int
    { 
        int i;
    };

    namespace std{
    template <>
    void swap<Int>(Int& a,Int& b)
    {
        Int temp;
        temp=a;
        a=b;b=temp;
    }
    }


    int main()
    {
        Int a1,b1;
        std::cin>>a1.i>>b1.i;
        swap(a1,b1);
        std::cout<<a1.i<<std::endl<<b1.i<<std::endl;
    }
Murugan P
  • 11
  • 5