我有一个问题可能已经被回答了 9000 多次,但我真的不知道如何措辞,这就是我要尝试的。
我在一些 C++ 书籍和教程中看到,在定义您自己的具有可迭代值(可递增)语义的类时,您可以operator++
为它重载(我将在这里陈述的所有内容我猜也适用operator--
)。这样做的标准方法似乎是:
class MyClass {
public:
MyClass& operator++ () {
increment_somehow();
return *this;
}
....
};
好在哪里increment_somehow()
......以某种方式增加了对象的价值。
然后,可以以operator++
如下方式定义后缀版本:
MyClass operator++ (MyClass& it, int dummy) {
MyClass copy(it);
++it;
return copy;
}
一切都很好而且花花公子(我认为我的成语是正确的),但问题是为每个operator++
快速定义的类做所有这些变得令人厌烦和冗长,所以我想我可以利用我的一个技巧最近在重载运算符时学到了。也就是说,利用我昨天发现的<utility>
标题和内部调用的工具(我在离开四年rel_ops
后才回到 C++ ......):
class MyClass {
public:
bool operator== (const MyClass& that) {
return compare_for_equality_somehow(that);
}
bool operator< (const MyClass& that) {
return compare_for_lessality_somehow(that);
}
....
using namespace std::rel_ops; // operators >, >=, <=, ! are "magically" defined!
};
(我只是出于类比的目的发明了“lessality”这个词,我的脑袋由于某种原因拒绝提出正确的数学术语......)
I created a simple header <step_ops.hpp>
whose content somewhat imitates the std::rel_ops
namespace found in the Utility header. Fro what I can see after a couple of compiles, it just works(TM). Can I / Should I use this trick? What are possible pitfalls I could come up against if I create a class and use a using namespace MyLibrary::increment_operators
(for example)?
And maybe much, MUCH more important: Have I just reinvented the wheel again, or have I just created a useful small library that could be aggregated to such kinds of projects? Pretty much any experiments that I have tried to do with C++ to get myself back up-to-speed and collaborate stuff seem to already be covered under a boost::do_something
facility and it makes me kind of sad that I have spent so much time away.