[英]Why does ADL take precedence over a function in 'std namespace' but is equal to function in user-defined namespace?
[英]std::equal function with user-defined class
我正在尝试了解一些示例代码(请参见下文)。 我对std:equal函数的理解是,当使用用户定义的类型时,必须定义一个等于==的运算符,以允许该函数执行比较。
所以我不明白这个int()运算符(是否是强制转换?)如何执行相同的功能。 为什么相等函数会尝试将A类的实例强制转换为int?
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;
struct A
{
int a;
A(int a) : a(a) {}
operator int() const { return a; } //LINE I
};
int main()
{
set<A> s{ 3, 9, 0, 2, 1, 4, 5, 6, 6, 9, 8, 2 };
cout << equal(s.begin(), s.end(), s.begin()) << endl; //LINE II
}
通过查看以下代码,您可以了解发生了什么:
#include <iostream>
class A {
public:
int a;
A(int a) : a(a) {}
//operator int() const {return a;}
};
int main () {
A a{10};
A b{20};
std::cout << std::boolalpha << (a == b) << std::endl; // does not compile
}
如果您注释转换运算符,则代码不进行比较。 如果取消注释,则代码将编译,并且比较是通过将a
和b
隐式转换为int
。
之所以执行此转换,是因为int
s的标准运算符==
是评估表达式a == b
的良好候选者,因此编译器触发了对int
的隐式转换(感谢@LightnessRacesinOrbit指出了这一点)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.