3

assume that i have this code:

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

what is the difference between:

  1. overloading

    void Swap (int& x, int& s)
    {
        //some behavior 
    }
    
  2. Specialization

    template<> void Swap <int> (int& x, int& s)
    {
        //some behavior 
    }
    

and who is better?

asaf app
  • 384
  • 2
  • 3
  • 12
  • Overload resolution selects an overload, and if that overload happens to be a template, _then_ the compiler checks for specializations that fit the argument types. – Xeo Apr 01 '14 at 13:03

1 Answers1

0

Overloading defines a method with the same name and the compiler will not try to make template type deduction in case it finds this overloaded method and it fits the parameter types it is being called with. A simple call, like:

    int a = 1, b = 2;
    Swap(a,b);         // calls the overloaded method

will go to the overloaded method.

For calling the specialized method you need explicitly tell the compiler:

    Swap<int>(a,b);    // calls the specialized method
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167