【问题标题】:Weird operator overloading, "operator T& () const noexcept { return *_ptr; }"奇怪的运算符重载,“运算符 T& () const noexcept { return *_ptr; }”
【发布时间】:2016-11-05 23:03:59
【问题描述】:

我研究了算子函数的格式是

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

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

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

【问题讨论】:

  • 我在问创建强制转换的语法是什么(在 C# 中它与此非常相似)
  • 转换运算符的格式不同。

标签: c++ class c++11


【解决方案1】:

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&amp; operator () const noexcept; 尝试声明operator(),但由于缺少参数列表而无法编译。正确的语法是:

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

还有usage is completely different

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    相关资源
    最近更新 更多