std::optional<T> 赋值运算符

std::optional<T> assignment operators

提问人:Vinod 提问时间:9/25/2023 最后编辑:Vinod 更新时间:9/26/2023 访问量:43

问:

我的参考是 std::optional::operator= 的选项 (4)、(5) 和 (6)

鉴于

The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.

(4)从描述中的链接状态:

The function does not participate in overload resolution unless std::decay_t<U> (until C++20)std::remove_cvref_t<U> (since C++20) is not std::optional<T>, std::is_constructible_v<T, U> is true, std::is_assignable_v<T&, U> is true, and at least one of the following is true:

    T is not a scalar type;
    std::decay_t<U> is not T.

上面的含义似乎是不是,但既然可能是,这个条件如何与另一个条件相关Ustd::optional<T>std::optional<T>T

std::is_constructible_v<T, U> is true, std::is_assignable_v<T&, U> is true

另外,如果不是标量类型,如果不是,赋值怎么可能起作用?Tstd::decay_t<U>T

(5)和(6)状态

These overloads do not participate in overload resolution unless the following conditions are met:

    T is not constructible, convertible, or assignable from any expression of type (possibly const) std::optional<U>, i.e., the following 12 type traits are all false:
        std::is_constructible_v<T, std::optional<U>&>
        std::is_constructible_v<T, const std::optional<U>&>
        std::is_constructible_v<T, std::optional<U>&&>
        std::is_constructible_v<T, const std::optional<U>&&>
        std::is_convertible_v<std::optional<U>&, T>
        std::is_convertible_v<const std::optional<U>&, T>
        std::is_convertible_v<std::optional<U>&&, T>
        std::is_convertible_v<const std::optional<U>&&, T>
        std::is_assignable_v<T&, std::optional<U>&>
        std::is_assignable_v<T&, const std::optional<U>&>
        std::is_assignable_v<T&, std::optional<U>&&>
        std::is_assignable_v<T&, const std::optional<U>&&>. 

同样,可能是 ,如果是这样,分配如何进行?std::optional<U>U

描述进一步写道:

For overload (5), std::is_constructible_v<T, const U&> and std::is_assignable_v<T&, const U&> are both true.
For overload (6), std::is_constructible_v<T, U> and std::is_assignable_v<T&, U> are both true

如果包含,情况会不会是这样吗?std::optional<U>U

是否应该并假设没有有效的值来解决上述明显的矛盾?std::optional<T>std::optional<U>

基于下面的测试代码,并且是不同的类型。std::optional<T>T

#include<optional>
#include<type_traits>
#include<string>
#include<ios>
#include<iostream>

using std::optional;
using std::is_same;
using std::string;
using std::boolalpha;
using std::cout;
using std::endl;

int main (){
  optional<string> opt("yes");
  string s("yeah"); 

  cout << boolalpha << is_same<decltype(opt),decltype(s)>::value << endl;

  return 0;
}
c++17 赋值运算符 std可选

评论


答: 暂无答案