Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...