简体   繁体   English

“ const”,“&”和“ &&”如何影响无参数函数的重载?

[英]How do “const”, “&”, and “&&” affect overloading of a parameterless function?

Consider a class defined as below: 考虑定义如下的类:

struct A
{
    void f();
    void f() const;
    void f() &;
    void f() const &;
    void f() &&;
    void f() const &&;
};

What are the differences between: 之间有什么区别?

1) void A::f(); 1)无效A :: f(); and void A::f() &; 并无效A :: f()&; (Please notice this!) (请注意这一点!)

2) void A::f() const; 2)void A :: f()const; and void A::f() const &; 并无效A :: f()const&;

3) void A::f() &&; 3)无效A :: f()&&; and void A::f() const &&; 和无效的A :: f()const &&;

You can transform these to 您可以将它们转换为

void f(A&);
void f(const A&);

void f(A&);
void f(const A&);
void f(A&&) &&;
void f(const A&&);

The first is special - it is a A& , but still accepts rvalues , unlike other non-const lvalue references. 第一个是特殊的-它是A&但是仍然接受rvalue ,这与其他非常量lvalue引用不同。 In all other regards, it is the same as any other function with a A& parameter. 在所有其他方面,它与带有A&参数的任何其他函数相同。

There is no difference in overload resolution between the second ( const ) and the fourth ( const&) , except if they respectively compete against a ( && ). 第二个( const )和第四个( const&)之间的重载分辨率没有区别,除非它们分别与( && )竞争。 I don't think that can happen for normal functions, but only for conversion functions, because the Standard forbids this case (in general, if there is any function in the current scope with a ref qualifier, all functions must) 我认为普通函数不会发生这种情况,而是转换函数会发生这种情况,因为标准禁止这种情况(通常,如果当前作用域中有任何带有ref限定符的函数,则所有函数都必须)

void f();
void f() &&;

But with conversion functions, you can still have an overload resolution set with both operator int() and operator long()&& . 但是,使用转换函数,您仍然可以同时设置operator int()operator long()&&的重载分辨率。 In that case, even if the object on which they are invoked is R() (an rvalue), if you need to convert to int then the first conversion function would be used. 在那种情况下,即使调用它们的对象是R() (一个右值),如果您需要转换为int ,也将使用第一个转换函数。

  1. f() is a normal function for f() const , this must point to a modifiable lval f()为正常功能f() constthis必须指向可修改lval中
  2. f() const is a const function (cannot change this) f() const & is the same but guarantees this is an lval as well f() const是const函数(无法更改) f() const &相同,但也保证这也是lval
  3. f()&& this must be a temporary value for f() const && this must be a temporary value that you cannot modify f()&&这必须是f() const &&的临时值f() const &&这必须是您不能修改的临时值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM