如果没有其他重载(例如
但如果存在上述语法,那将会非常好。即
另一个序列可以用来表示成员函数cv-ref-qualifier和cv-ref-qualified类型,即
关于这个问题,是否有关于在C++17中使用的提案呢?
f(T &)
或f(volatile T &&)
)(成员)函数模板template< typename T > f(T &&);
,那么T &&
被称为转发引用,而T
是U
,或者对于某些cv限定类型U
,T &
。但是对于成员函数的cv-ref限定符,没有这样的规则。在struct S { void f() && { ; } };
中,S::f()
总是具有rvalue引用限定符。
在通用代码中,如果所有重载函数都执行相同的操作,则避免定义4个(甚至8个,如果我们还考虑volatile
限定符)某个成员函数的重载函数将非常有用。
另一个问题是,在这种方式下无法定义*this
的有效cv-ref限定符。以下代码不允许确定成员函数operator ()
的ref限定符是&&
还是&
。
#include <type_traits>
#include <utility>
#include <iostream>
#include <cstdlib>
#define P \
{ \
using this_ref = decltype((*this)); \
using this_type = std::remove_reference_t< this_ref >; \
std::cout << qual() << ' ' \
<< (std::is_volatile< this_type >{} ? "volatile " : "") \
<< (std::is_const< this_type >{} ? "const " : "") \
<< (std::is_lvalue_reference< this_ref >{} ? "&" : "&&") \
<< std::endl; \
}
struct F
{
constexpr int qual() & { return 0; }
constexpr int qual() const & { return 1; }
constexpr int qual() && { return 2; }
constexpr int qual() const && { return 3; }
constexpr int qual() volatile & { return 4; }
constexpr int qual() volatile const & { return 5; }
constexpr int qual() volatile && { return 6; }
constexpr int qual() volatile const && { return 7; }
void operator () () & P
void operator () () const & P
void operator () () && P
void operator () () const && P
void operator () () volatile & P
void operator () () volatile const & P
void operator () () volatile && P
void operator () () volatile const && P
};
int
main()
{
{
F v;
F const c{};
v();
c();
std::move(v)();
std::move(c)();
}
{
volatile F v;
volatile F const c{};
v();
c();
std::move(v)();
std::move(c)();
}
return EXIT_SUCCESS;
}
但如果存在上述语法,那将会非常好。即
decltype((*this))
表示*this
的确切cv-ref-qualified类型。在我看来,引入这样的语法到C++标准的即将推出的版本中并不会产生破坏性变化。但是,&&
作为forwarding cv-ref-qualifier是可以的(而且它看起来像是委员会遗漏了的事情(即核心语言工作组))。另一个序列可以用来表示成员函数cv-ref-qualifier和cv-ref-qualified类型,即
auto &&
、decltype(&&)
等。关于这个问题,是否有关于在C++17中使用的提案呢?
&
或&&
,可能值得单独提出一个问题。例如,这与前向引用并不相关(相反),而您正在使用它来比较我认为是主要问题的内容。 - Luc Danton