带有函数签名的Const关键字

Sup*_*rxy 3 c++ stl const function

这是我的简单代码:

#include <iostream>

using namespace std;

class alloc { };

template <typename T, typename Alloc = alloc>
class vector
{
public:
    void swap(vector<T,Alloc> &v) { cout << "swap()" << endl; }
};


template <typename T, typename Alloc>
void swap(const vector<T,Alloc> &v1,const vector<T,Alloc> &v2)
{
    v1.swap(v2);
}

int main()
{
    vector<int> x;
    vector<int> y;

    swap(x,y);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码片段运行没有问题.但我无法获得任何输出

然后我删除const关键字.

void swap(vector<T,Alloc> &v1,vector<T,Alloc> &v2)
Run Code Online (Sandbox Code Playgroud)

我得到输出 swap()

我读过"原因是参数的const只在函数中本地应用,因为它正在处理数据的副本.这意味着函数签名实际上是相同的."

所以我认为写或不写const之间没有区别.如果我坚持在这里写const,我如何修改代码以获得输出 swap()

das*_*ght 7

这是为什么using std应该避免的一个很好的例子.

要调试此问题,请删除using std并添加std::您希望标准库中的行为的位置.幸运的是,只有一个这样的地方,即swap模板类中的函数:

void swap(vector<T,Alloc> &v) { std::cout << "swap()" << std::endl; }
Run Code Online (Sandbox Code Playgroud)

现在再次尝试编译以查看阻止swap使用该错误的错误const:

prog.cpp:19:5:错误:const vector<int>作为this参数传递会丢弃限定符

当你的程序是using stdC++ 时,你可以选择std::swap在你的swap函数不适用时挑选你自己的函数.这正是它所做的,没有任何警告,因为它假设它是你想要它做的.

该错误还告诉您如何使const接受限定的向量:添加const到参数中vector::swap,如下所示:

void swap(const vector<T,Alloc> &v) const { std::cout << "swap()" << std::endl; }
Run Code Online (Sandbox Code Playgroud)

现在你的程序编译并再次运行(演示).