l-value ref限定成员函数和非限定成员函数之间的区别?
Difference between l-value ref-qualified member function and unqualified member function?
左值引用限定成员函数和非限定成员函数之间有区别吗?如果有,那是什么?
也就是说,这两种声明方式 func()
不同吗?
class Foo
{
void func();
void func() &;
};
我不是说 "are they different enough to permit overload resolution,",因为当 func()
的两个版本都存在时,上面的 class 显然无法编译。我的意思是,当包含 &
与不包含时,编译器的行为方式和原因为何不同?
至少有一个区别,即引用限定函数(左值或右值类型)不能用非引用限定函数重载。来自 current standard draft:
Member function declarations with the same name and the same
parameter-type-list as well as member function template
declarations with the same name, the same parameter-type-list, and
the same template parameter lists cannot be overloaded if any of them, but not
all, have a ref-qualifier.
...但如果这是唯一的区别,为什么要限制?即,为什么 foo()&&
不能被视为(不合格)foo()
的有效覆盖?
它们是不同的。
Foo foo;
std::move(foo).func();
会调用 func()
但不会调用 func()&
。
同样:
Foo make_foo() { return {}; }
make_foo().func();
仅适用于 void func()
签名,不适用于 void func()&
签名。
void func()&
意味着它只是对左值而不是右值的有效调用。
左值引用限定成员函数和非限定成员函数之间有区别吗?如果有,那是什么?
也就是说,这两种声明方式 func()
不同吗?
class Foo
{
void func();
void func() &;
};
我不是说 "are they different enough to permit overload resolution,",因为当 func()
的两个版本都存在时,上面的 class 显然无法编译。我的意思是,当包含 &
与不包含时,编译器的行为方式和原因为何不同?
至少有一个区别,即引用限定函数(左值或右值类型)不能用非引用限定函数重载。来自 current standard draft:
Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.
...但如果这是唯一的区别,为什么要限制?即,为什么 foo()&&
不能被视为(不合格)foo()
的有效覆盖?
它们是不同的。
Foo foo;
std::move(foo).func();
会调用 func()
但不会调用 func()&
。
同样:
Foo make_foo() { return {}; }
make_foo().func();
仅适用于 void func()
签名,不适用于 void func()&
签名。
void func()&
意味着它只是对左值而不是右值的有效调用。