不能只删除方法的常量重载?
Can't delete only const overload of method?
至少使用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
获取实例的地址。
相关文章:
- 什么时候可以使用常量装饰调用我的重载函数?
- 如何为非常量和常量重载实现一次成员函数?
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 重载模板化类的[]运算符的常量版本
- 引用模板类型的赋值运算符需要非常量重载
- MSVC:推理指向具有常量和非常量重载的成员函数的指针
- 为什么 lambda 自动和参数选择常量重载?
- 非常量指针更喜欢常量 T&重载而不是常量 T*
- asio_handler_invoke常量重载
- 不能只删除方法的常量重载?
- 如何获取提供常量重载的函数类型
- 基于常量重载
- 二元运算符 + , = 使用常量重载
- 如何检查成员函数是否具有常量重载
- C++使用一个参数常量重载
- 为什么常量左值与给定 T&& 和常量 T& 重载的常量右值绑定不同?
- 指向常量重载成员函数的指针
- 常量重载和共享指针
- c++非常量-常量重载方法选择
- 如何调用非常量重载