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

时间:2016-07-04 09:13:36

标签: c++ class c++11

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

(return value)operator[space]op(arguments){implementation}

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

此运算符与T& operator () const noexcept { return *_ptr; }不同吗?如果两者不同,那么第一个是什么用?

1 个答案:

答案 0 :(得分:11)

operator T& () const noexcept;user-defined conversion functionstd::reference_wrapper拥有它,以便您无需更改语法即可访问存储的引用:

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

std::cout << a << " " << b << std::endl;

Assignment is a little bit trickier

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

T& operator ()( ) const noexcept;
//             ^
//       parameters here

usage is completely different