奇怪的运算符重载,"运算符T&()const noexcept {return*_ptr;}"

Job*_*bin 5 c++ class c++11

我研究过运算符函数的格式是

(return value)operator[space]op(arguments){implementation}
Run Code Online (Sandbox Code Playgroud)

但是,在std::reference_wrapper实现中,有一个声明为的运算符重载函数operator T& () const noexcept { return *_ptr; }.

这个操作符与T& operator () const noexcept { return *_ptr; }?不同?如果两者不同,那么第一个的用途是什么?

Log*_*uff 11

operator T& () const noexcept;用户定义的转换函数.std::reference_wrapper有它,以便您可以访问存储的引用,而无需更改语法:

int x = 42;
int &a = x;
std::reference_wrapper<int> b = x;

std::cout << a << " " << b << std::endl;
Run Code Online (Sandbox Code Playgroud)

作业有点棘手.


T& operator () const noexcept;是尝试声明operator(),但由于缺少参数列表而无法编译.正确的语法是:

T& operator ()( ) const noexcept;
//             ^
//       parameters here
Run Code Online (Sandbox Code Playgroud)

使用是完全不同的.