2014-08-28 61 views
0

我正在从一种编程风格移动到另一种编程风格的代码库。C++技巧来避免指针比较

我们定义了一个名为Operand类型,如:

class Operand 
{...}; 

然后我们有

class OperandFactory 
{ 
    public: 
    const Operand *make_operand (...); 
}; 

用于散列Operand,并保持在一个表OperandFactory。因此,如果您使用相同的参数调用make_operand,则您将获得与Operand相同的指针和指针比较。现在我需要添加一个功能,这将使这不可行。所以,我在Operand中实现了operator==,并且如果我在Operand上做了指针比较,我希望以某种方式在编译时(更好)或运行时(好于没有)错误生成。达到此目的的最佳方式是什么?

这只是在这个过渡阶段使用,所以我不介意解决方案看起来像一个黑客,只要它捕获代码库中的所有比较。

+1

显示代码或至少是您实际尝试实现的最小工作简化示例。 – Alex 2014-08-28 13:03:44

回答

3

您可以重载操作符的地址以返回句柄并声明两个句柄(没有定义)的比较。这会导致链接器错误。

#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 */ 
    } 

} 

注意

你必须履行Handlerandom_access_iterator要求!

Op i{10} 
Handle ref = &i; 

ref++; ref--; ++ref; --ref; ref = ref + 10; ref = ref - 10; // should all work. 
+1

您可以使用'= delete'(自C++ 11以来)具有编译器错误而不是链接器错误。 – Jarod42 2014-08-28 13:39:46

2

在您的Operand类中添加运算符将无济于事:要检测指针Operand s的比较结果。不幸的是,本地类型操作符不能被重载,指针是本机类型的。这不是你正在寻找的解决方案。

+4

您可以重载操作符的地址以返回句柄并声明两个句柄(没有定义)的比较。这会导致链接器错误。 – Alex 2014-08-28 13:06:31

+0

开箱即用思考。你说对了。 – Quentin 2014-08-28 13:09:26