且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么std :: optional :: operator =(U&)要求U是非标量类型?

更新时间:2022-03-23 04:01:46

存在的目的在于: / p>

This exists to support:

optional<int> o(42);
o = {}; // <== we want this to reset o

我们有一堆分配超载,其花费为:

We have a bunch of assignment overloads, which take:


  1. nullopt_t

  2. 可选const&

  3. 可选&&

  4. U&& ;

  5. optional< U> const&

  6. 可选< U>&

  1. nullopt_t
  2. optional const&
  3. optional&&
  4. U&&
  5. optional<U> const&
  6. optional<U>&&

对于标量,具体来说,#4将是标准转换,而其他则将是用户定义的转换-因此这将是***匹配。但是,这样做的结果是将 o 分配给值为 0 的用户。这意味着 o = {} 可能根据 T 的类型可能具有不同的含义。因此,我们排除了标量。

For scalars, specifically, #4 would be a standard conversion whereas anything else would be a user-defined conversion - so it would be the best match. However, the result of that would be assigning o to be engaged with a value of 0. That would mean that o = {} could potentially mean different things depending on the type of T. Hence, we exclude scalars.

对于非标量,#4和#3等效(都是用户定义的转换),而#3将成为非模板而获胜。没问题。

For non-scalars, #4 and #3 would be equivalent (both user-defined conversions), and #3 would win by being a non-template. No problem there.