为什么我的自定义"::swap"函数没有被调用?
Why is my customed `::swap` function not called?
在这里,我编写了一个代码片段来查看将调用哪个swap
,但结果两者都不是。不输出任何内容。
#include<iostream>
class Test {};
void swap(const Test&lhs,const Test&rhs)
{
std::cout << "1";
}
namespace std
{
template<>
void swap(const Test&lhs, const Test&rhs)
{
std::cout << "2";
}
/* If I remove the const specifier,then this will be called,but still not the one in global namespace,why?
template<>
void swap(Test&lhs, Test&rhs)
{
std::cout << "2";
}
*/
}
using namespace std;
int main()
{
Test a, b;
swap(a, b);//Nothing outputed
return 0;
}
哪个swap
叫?在另一种情况下,为什么被称为没有const
说明符的专用swap
,而不是::swap
?
std::swap()
类似于[ref]
template< class T >
void swap( T& a, T& b );
它比你的更好匹配
void swap(const Test& lhs, const Test& rhs);
为
swap(a, b);
其中a
和b
是非恒常量。所以调用std::swap()
,它不输出任何内容。
请注意,由于using namespace std;
,std::swap()
参与重载解析。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 函数何时会在c++中包含stack_Unwind_Resume调用