我正在将代码库从一种编程风格转移到另一种编程风格。
我们有一个名为 Operand
的类型,定义如下:
class Operand
{...};
然后我们有
class OperandFactory
{
public:
const Operand *make_operand (...);
};
OperandFactory
用于散列Operand
并将其保存在表中。因此,如果您使用相同的参数调用 make_operand
,您将获得相同的指针,并且对 Operand
的指针比较会激增。现在我需要添加一个功能,使它变得不可行。所以,我在 Operand
中实现了 operator==
并且如果我做了一个指针,我想以某种方式在编译时(更好)或运行时(总比没有好)生成错误Operand
的比较。实现这一目标的最佳方法是什么?
这只会在这个过渡阶段使用,所以我不介意这个解决方案是否看起来像 hack,只要它捕获代码库中的所有比较即可。
最佳答案
您可以重载运算符的地址以返回句柄并声明两个句柄的比较(无需定义)。这将导致链接器错误。
#include <iostream>
class Op;
class Handle {
Op *pri_;
public:
explicit Handle(Op *o) : pri_(o) {}
Op *operator->() const { return pri_; }
Op &operator*() const { return *pri_; }
};
// force compile time errors on comparison operators
bool operator==(const Handle &, const Handle &) = delete;
bool operator!=(const Handle &, const Handle &) = delete;
bool operator>=(const Handle &, const Handle &) = delete;
bool operator<=(const Handle &, const Handle &) = delete;
bool operator<(const Handle &, const Handle &) = delete;
bool operator>(const Handle &, const Handle &) = delete;
class Op {
int foo_;
public:
explicit Op(int i) : foo_(i) { }
Handle operator&() { return Handle(this); };
void touch() const { std::cout << "foobar"; }
};
int main(int argc, char **argv) {
Op i{10};
Op j{20};
auto c = &j; // works
c->touch(); // works
(*c).touch(); // works
if (&j == &i) {
/* will not compile */
}
}
注意:
您必须满足 Handle
的 random_access_iterator
要求!
Op i{10}
Handle ref = &i;
ref++; ref--; ++ref; --ref; ref = ref + 10; ref = ref - 10; // should all work.
关于避免指针比较的 C++ 技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549422/