简体   繁体   English

C ++中的模板类?

[英]Template class in c++?

I am using a template class to set the data type for a swap function. 我正在使用模板类来设置交换函数的数据类型。 In the code if i initialize the function name as lower case letter it throws an error call of overloaded 'swap(double&, double&) is ambiguous but when i initialize the function name as upper case it works fine. 在代码中,如果我将函数名初始化为小写字母,则会抛出一个错误call of overloaded 'swap(double&, double&) is ambiguous错误call of overloaded 'swap(double&, double&) is ambiguous但是当我将函数名初始化为大写时,它可以正常工作。 Will appreciate if someone could explain me why this is happening. 如果有人能解释我为什么会发生,将不胜感激。 Here is my code 这是我的代码

#include<iostream>

using namespace std;
template <class T>
void swap(T &a,T &b)
{
    T temp;

    temp = a;
    a = b;
    b = temp;
}

int main()
{
    double value1 = 2.44;
    double value2 = 6.66;

    cout<<"\tBefore swap \n";
    cout<<"Value 1 = "<< value1 <<"\tValue 2 = " << value2 <<"\n";

    swap(value1,value2);

    cout<<"\tafter swap \n";
    cout<<"Value 1 = "<< value1 <<"\tValue 2 = "<<value2;
}

Instead of 代替

swap(value1,value2);

use 采用

::swap(value1,value2);

This would solve the namespace and ambiguity issue. 这将解决名称空间和歧义性问题。

because there is already a standard library function std::swap http://www.cplusplus.com/reference/algorithm/swap/ so possibly your compiler does not like it? 因为已经有一个标准的库函数std::swap http://www.cplusplus.com/reference/algorithm/swap/,所以您的编译器可能不喜欢它? You pull that in via using namespace std; 您可以通过using namespace std;

Change the name of your swap function because std::swap already exists. 更改swap功能的名称,因为std::swap已经存在。

Or you could put it in a separate namespace and use the scope resolution operator, "::", to distinguish yours from the standard one. 或者,您可以将其放在单独的名称空间中,并使用范围解析运算符“ ::”将您的名称与标准名称区分。

This is what happens when you use namespace std; 这是在使用namespace std;时发生的情况namespace std; . You may want to be more specific and use: 您可能需要更具体地使用:

using std::cout;
using std::endl;
using std::cin;

Already standard library function is defined with templates 'swap' Instead of 'SWAP',It is actually under the std namespace, but because you have a using namespace std line, it exists without the std:: prefix. 已经使用模板'swap'而不是'SWAP'定义了标准库函数,它实际上位于std名称空间下,但是由于您具有using namespace std行,因此它没有std ::前缀。

As you can see, using the using namespace std isn't always a good option because of possible name collisions, as in this example. 如您所见,由于本例中可能发生名称冲突,因此使用using名称空间std并非总是一个好的选择。 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. 通常,除非存在真正的原因(名称空间存在是出于某种原因)以防止名称冲突,否则通常不应该使用using指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM