c++ - 这个 C++ 模板声明真的不正确还是我的编译器搞砸了?

标签 c++

编辑:感谢您的回答!就像我说的,这是为类提供的代码,因此包含了 namespace 和函数名称。不过,我很高兴了解命名空间 std 到底包含什么,并且我已将您的意见作为评论包含在我的回答中(尽管我的回答保持不变)。

下面的代码包括我创建的片段。这是一个类,所以这是唯一我需要判断的部分。我的编译器没有运行它(对重载函数的模糊调用)但我觉得这是正确的。

template <class data_type>
void swap(data_type &a, data_type &b) //swaps 2 variables
{
   data_type c; //temp variable
   c = a;
   a = b;
   b = c;
}

完整代码如下:

#include <iostream>
#include <string>

using namespace std;

template <class data_type>
void swap(data_type &a, data_type &b) //swaps variables
{
   data_type c;
   c = a;
   a = b;
   b = c;
}

int main( )
{
    string x = "first", y = "second";
    int m = 10, n = 20;
    char q = 'Q', r = 'R';

    cout<<"x before swap called = "<<x<<" and y before swap called = "
<<y<<endl;
    swap(x,y);
    cout<<"x after swap called = "<<x<<" and y after swap called = "
<<y<<endl<<endl;

    cout<<"m before swap called = "<<m<<" and n before swap called = "
<<n<<endl;
    swap(m,n);
    cout<<"m after swap called = "<<m<<" and n after swap called = "
<<n<<endl<<endl;

    cout<<"q before swap called = "<<q<<" and r before swap called = "  
<<r<<endl;
    swap(q,r);
    cout<<"q after swap called = "<<q<<" and r after swap called = "   
<<r<<endl<<endl;

    return 0;
}

最佳答案

标准库带有一个模板std::swap(参见cpp reference),您正在定义自己的swap-模板函数。到目前为止没问题,但是一旦声明 using namespace std,任何 swap 的使用都是不明确的,因为编译器无法决定是否采用 std::swap 或您自己的 swap

因此,正如其他人已经提到的那样,避免使用 using namespace std 语句。

此外,您可以考虑在自己的命名空间中声明“您的”swap,例如:

namespace class1_exercise {

    template <class data_type>
    void swap(data_type &a, data_type &b) //swaps variables
    {
        data_type c;
        c = a;
        a = b;
        b = c;
    }
}

因此,您可以更加明确地区分“您的”交换和 std::swap:

std::swap(x,y);
// versus:
class1_exercise::swap(x,y);

关于c++ - 这个 C++ 模板声明真的不正确还是我的编译器搞砸了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240609/

相关文章:

c++ - OpenCV CUDA calcOpticalFlowBM

转发通用引用的 C++ 存储函数

c++ - 涉及虚函数的C++代码的输出说明

c++ - C++ 中 const 声明的区别

c++ - boost::circular_buffer 如何处理覆盖移位

c++ - 是否有像 auto_ptr 和 shared_ptr 这样不需要 C++0x 的通用智能指针?

c++ - 如何将析构函数分配给指针?

c++ - 如何在 Visual Studio 6.0 调试器中观察 std::wstring var

c++ - 如何在Windows composer中集成Qt无框窗口? (系统快捷方式不起作用)

c++ - 从不兼容的类型分配给 Double?