Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a template error if I name my function `swap`, but `Swap` is okay?

Tags:

c++

templates

Alright so heres the program and works absolutely right

#include <iostream>

using namespace std;

template <typename T>
void Swap(T &a , T &b);

int main(){

    int i = 10;
    int j = 20;

    cout<<"i, j = " << i <<" , " <<j<<endl;
    Swap(i,j);
    cout<<"i, j = " << i <<" , " <<j<<endl;


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

but when I change the function's name from Swap to swap it generates an error saying

error: call of overloaded 'swap(int&, int&)' is ambiguous| note: candidates are: void swap(T&, T&) [with T = int]| ||=== Build finished: 1 errors, 0 warnings ===|

what happened is it a rule to start functions using templates to start with a capital letter ?

like image 611
Nash Vail Avatar asked Nov 10 '12 15:11

Nash Vail


1 Answers

This is because there already exists a function called swap. It is actually under the std namespace, but because you have a using namespace std line, it exists without the std:: prefix.

As you can see, using the using namespace std isn't always a good option because of possible name collisions, as in this example. In general one should prefer not to use the using directive unless there's a real reason for this - namespaces exist for a reason - to prevent name collisions.

like image 150
zxcdw Avatar answered Sep 30 '22 06:09

zxcdw