我遇到了这段代码,我不知道这是什么,有人可以向我解释一下吗?
template<class T> base{
protected:
T data;
public:
...
T&& unwrap() && { return std::move(data); }
operator T&&() && { return std::move(data); }
}
我知道operator T&&()
是cast operator,但我无法弄清楚粗体&amp;&amp; 的含义是什么:
运营商T&amp;&amp;()&amp;&amp; 要么 T&安培;&安培; unwrap()&amp;&amp;
答案 0 :(得分:0)
成员函数上的&&
和&
限定符表示以下内容:
&
限定函数&&
限定函数示例:强>
#include <iostream>
class Example
{
private:
int whatever = 0;
public:
Example() = default;
// Lvalue ref qualifier
void getWhatever() & { std::cout << "This is called on lvalue instances of Example\n"; }
// Rvalue ref qualifier
void getWhatever() && { std::cout << "This is called on rvalue instances of Example\n"; }
};
int main()
{
// Create example
Example a;
// Calls the lvalue version of the function since it's called on an lvalue
a.getWhatever();
// Calls rvalue version by making temporary
Example().getWhatever();
return 0;
}
这个输出是:
This is called on lvalue instances of Example
This is called on rvalue instances of Example
因为在第一个函数调用中,我们在Example
的左值实例上调用它,但在第二个调用中,我们将它作为临时函数调用该函数,调用rvalue限定函数。