在 C++ 中自动推导运算符?
在 C++ 中,编译器/语言是否可以自动推导未实现的运算符?
例如,如果我有:
class X
{
public:
bool operator ==(const X &x) const;
};
有没有办法隐式推导 != ?
我将利用这个问题来解决一个半相关的问题:为什么映射的键的唯一要求是实现 <<操作员?它如何比较平等?
Is it possible in C++ for the compiler/language to automatically deduce unimplemented operators?
For example, if I have:
class X
{
public:
bool operator ==(const X &x) const;
};
Is there a way for != to be deduced implicitly?
And I'll exploit this questions for a semi-related one: How come map's only requirement from it's keys is to implement the < operator? How does it compare for equality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
关于相关问题,它是一个等价类。两个事物 'x' 和 'y' 是等价的,如果
Regarding the related question, it's an equivalence class. Two things 'x' and 'y' are equivalent if
STL 已经有一组定义。
在命名空间 stl::rel_ops 中可以找到以下定义。
要使用它,你只需要这样做:
尽管我个人会尽可能限制使用范围。
The STL already has a set of definitions.
In the namespace stl::rel_ops the following definitions can be found.
To use it you just need to do:
Though personally I would restrict the scope of the using as much as possable.
Boost 运算符可以做你想做的事。
至于你的第二个问题:如果A不小于B且B不小于A,则两个值A和B相等。
boost operators can do what you want.
As for your second question: two values A and B are equal, if A is not less than B and B is not less than A.
C++的规则不允许大多数运算符的完全隐式推导,但您可以在“模板方法设计模式”模型中通过继承来模拟它;一个过于简单的例子...:
其他答案已经向您指出了一个基于巧妙模板和 c 的系统库,用于此类目的(增强)以及第二个问题的答案(一旦您有了
<
,所有需要的比较,包括相等性,都可以在 std 库代码中轻松实现 (<
)。Completely implicit deduction of most operators is not allowed by C++'s rules, but you can mostly simulate it with inheritance in the "template method design pattern" mold; an oversimplified example...:
Other answers have already pointed you to a systematic library based on clever templates &c for such purposes (boost) and to the answer for your second question (once you have
<
, all needed comparisons, including equality, can be easily implemented in the std library code in terms of<
).请参阅 Wikipedia 上的巴顿·纳克曼技巧。它利用 CRTP 习惯用法 和内联友元函数。
See Barton Nackman trick on Wikipedia. It makes use of the CRTP idiom and inline friend functions.