在 C++ 中取消引用这个指针是否有效?

问题描述

struct myclass{
    static const int invalid = -1;
    /*explicit*/ myclass(int i,double d = 0.0){
        _var = i
    }
    int _var; 
    bool operator < (const myclass& rhs);
    bool operator > (const myclass& rhs);
    bool operator == (const myclass& rhs);
    bool operator != (const myclass& rhs);
    /*
    bool operator == (int rhs){
        return *(this) == myclass(rhs); // Is this valid C++ ?
    }
    bool operator != (int rhs){
        return *(this) == myclass(rhs); // Is this valid C++ ?
    }
    */
};

int userCodeCall() {
    myclass m(10);
    
    // Valid use Case
    if(m != myclass::invalid) {
        //.... do something
    }
    
    // Invalid use case
    if(m < 0.5) { // I want this to give me a compiler error
        //.... do something
    }
    // Invalid use case
    if(m < 5) { // I want this to give me a compiler error
        //.... do something
    }
}

我正在处理遗留代码库,我遇到了一个可以从 int 隐式构造的类。我发现了一个错误,我们在执行

bool operator == (int rhs){
    return *(this) == myclass(rhs); // Is this valid C++ ?
}

我有两个问题?

  1. C++11/14/17 是否有效?

  2. 课程的设计可以改进吗?鉴于我仍然希望使用“==”比较样式来保持有效,因为它遍布整个用户代码库。

    if(m != myclass::invalid) // some similar API need to be supported,if not the same.
    

解决方法

您的解决方案很好,但您似乎只是想阻止特定的比较运算符在数字类型位于右侧时起作用。对于除 myclass 以外的所有类型,您只需删除这些特定运算符即可实现这一点。

template<typename T>
bool operator<(T) = delete;
    
template<typename T>
bool operator>(T) = delete;
,

这种有效性测试更常见的习惯用法是使用显式运算符 bool:

struct myclass {
 private:
    static const int _invalid = -1;
    int _var;
 public:
    explicit myclass(int i,double d = 0.0){
        _var = i
    } 
    explicit operator bool() const { return _var != _invalid; }
    bool operator < (const myclass& rhs);
    bool operator == (const myclass& rhs);
    bool operator != (const myclass& rhs);
    bool operator > (const myclass& rhs);
};

int userCodeCall() {
    myclass m(10);
    
    // Valid use Case
    if(m) {
        //.... do something
    }
    
    // Invalid use case
    if(m < 0.5) { // gives a compile error
        //.... do something
    }
    // Invalid use case
    if(m < 5) { // gives a compile error
        //.... do something
    }
}

如果这太多并且你必须有一个 myclass::invalid 来测试,你可以让它成为类的一个实例:

static constexpr myclass invalid(-1);