代码之家  ›  专栏  ›  技术社区  ›  bartop

编译器看不到CRTP基中的运算符+

  •  0
  • bartop  · 技术社区  · 7 年前

    以下面这段代码为例:

    template<class Derived>
    struct base {
        Derived operator++(int){
            auto tmp = static_cast<Derived &>(*this);
            ++static_cast<Derived &>(*this);
            return tmp;
        }
    };
    
    struct der : public base<der> {
        der &operator++(){
            return *this;
        }
    };
    
    int main(){
        der d;
        d++;/// <<< compilation error here
    }
    

    编译器出现以下错误:

    错误:没有为后缀“++”[-fpermissive]声明“operator++(int)”

    为什么我的后缀运算符对编译器不可见它是否包含某种类型的错误,或者它对我来说是未知的C++特征吗?这段代码能被修正吗 operator++ 会按预期工作吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   aschepler    7 年前

    你的两个函数同名, operator++ . 它的拼写与用标识符命名的函数不同。类成员查找的规则是,默认情况下,如果在派生类中找到具有名称的成员,则不检查基类。派生成员“隐藏”基础成员。

    避免隐藏具有不同签名的基类函数并允许重载解析选择最佳函数的常用方法是使用声明:

    struct der : public base<der> {
        der &operator++(){
            return *this;
        }
        using base<der>::operator++;
    };
    
        2
  •  1
  •   Pete Becker    7 年前

    替换名称 operator++ 带着名字 f (也就是用一个普通的成员函数尝试同样的事情)。你也会有同样的问题。编译器在 der ,所以它不会往里看 base<dir> . 重载只发生在同一范围内定义的函数之间。