Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于set 和map的比较操作符重载问题 #114

Open
senvenseaNana7mi opened this issue Oct 3, 2022 · 5 comments
Open

关于set 和map的比较操作符重载问题 #114

senvenseaNana7mi opened this issue Oct 3, 2022 · 5 comments

Comments

@senvenseaNana7mi
Copy link

friend bool operator==(const set& lhs, const set& rhs) { return lhs.tree_ == rhs.tree_; } friend bool operator< (const set& lhs, const set& rhs) { return lhs.tree_ < rhs.tree_; }
set.h第199行和200行
已经在类内定义了比较操作符,在类外又定义了一次,这样不会出现重定义的问题吗

@Evilrabbit520
Copy link

friend 的原型在类中出现,但是貌似友元函数不是成员函数吧,应该不会出现重定义的问题。

@frederick-vs-ja
Copy link
Contributor

不会重定义。类内的是非模板函数,它与函数模板不对应。

但这个设计会导致类外的 operator==operator< 函数模板不被选择,使用 ==< 时选择的是非模板函数。

@frederick-vs-ja
Copy link
Contributor

我想我们可以把 MyTinySTL 的所有比较运算符改成友元。虽然这和标准库不一致,但可能更好。
另外在 C++20 模式下不再需要单独的关系运算符或 operator!= ,仅提供 operator==operator<=> 即可。

@senvenseaNana7mi
Copy link
Author

我想我们可以把 MyTinySTL 的所有比较运算符改成友元。虽然这和标准库不一致,但可能更好。 另外在 C++20 模式下不再需要单独的关系运算符或 ,仅提供 和 即可。operator!=``operator==``operator<=>

谢谢解答!对类模板的友元了解的不是很透彻,请教一下大佬这里的friend bool operator==(const set& lhs, const set& rhs)set不加模板参数是因为是在类模板内声明并定义的吗。

@frederick-vs-ja
Copy link
Contributor

我想我们可以把 MyTinySTL 的所有比较运算符改成友元。虽然这和标准库不一致,但可能更好。 另外在 C++20 模式下不再需要单独的关系运算符或 ,仅提供 和 即可。 operator!=operator==operator<=>

谢谢解答!对类模板的友元了解的不是很透彻,请教一下大佬这里的friend bool operator==(const set& lhs, const set& rhs)set不加模板参数是因为是在类模板内声明并定义的吗。

是的,此处的 set注入类名injected-class-name),可以自动指代类模板的当前特化。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants