如何初始化用户定义数据类型的 std::optional

How to initialize the std::optional of a user defined data type

我正在尝试学习 C++ 17 的新功能。

请找到以下代码:

class Test
{
public:
      Test(int x):y(x){}
      ~Test(){}
      int getx()
      {
          return x;
      }
private:
      int x;
};
struct Container
{
    std::optional<Test> test;
};
int main()
{
    struct Container obj;
    // here i want to initialize the member "test" of 
    // struct Container
    obj.test = make_optional<Test>(10); ----> is this correct??
}

有人可以告诉我如何初始化 std::optional 吗?例如,如果我这样声明:

std::optional<Test> t

如何初始化它?

obj.test = make_optional<Test>(10);

----> is this correct??

是的。你也可以这样做:

obj.test = Test(10);