不能只删除方法的常量重载?

Can't delete only const overload of method?

本文关键字:常量 重载 方法 删除 不能      更新时间:2023-10-16

至少使用Unary &和Unary -,GCC似乎只会让您删除操作员的非const和const版本或无(可能会影响二进制操作员检查)。如下注释中所述,尽管我可以基于const成功超载,但我不能单独删除const或non-const Overload而不遇到编译错误。此行为标准是否符合标准?似乎违反直觉。

用GCC 5.4.0。

测试
#include <iostream>
struct A {
    // These both being defined at the same time is fine,
    // and whether or not x is const as expected will change
    // which overload you get.
    A* operator&() {
        std::cout << "hello" << std::endl;
        return this;
    }
    const A* operator&() const {
        std::cout << "world" << std::endl;
        return this;
    }

    // assuming both definitions above are commented out,
    // regardless of whether or not x is const
    // either one of these lines being present
    // will make the example not compile!
    // A* operator&() = delete;
    // const A* operator&() const = delete;

    // Finally if you have the const version defined and the non-const version deleted
    // or vice versa, it will compile as long as the one that you have defined
    // matches the constness of x.
};
int main(int argc, char** argv)
{
    A x;
    std::cout << &x << std::endl;
    return 0;
}

内置的operator&不参与过载分辨率([over.match.oper]/3.3)。

对于operator , unary operator & operator ->,内置候选人设置为空。

说您声明为删除以下的超载

const A* operator&() const = delete;

不管您是要拿const还是非const A的地址,上面的声明是唯一可行的候选人,导致汇编错误。

如果您发表评论,则根据[Over.match.oper]/9。

发现内置的operator&

如果操作员是operator , unary operator & operator ->,并且没有可行的功能,则假定操作员是内置的运算符并根据条款[expr]解释。

现在,如果您声明为已删除的非const Overload

A* operator&() = delete;

这不能在const A对象上调用,因此它不会是可行的候选者,并且会找到内置的operator&

实时演示


处理超载operator&的类时,您可以使用std::addressof获取实例的地址。