Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

I am trying to learn new features of C++ 17.

Please find the below code:

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??
}

Can someone please let me know how to initialize a std::optional? For example, if I declare it like:

std::optional<Test> t

How can I initialize it?

like image 366
sagar Avatar asked Sep 01 '25 05:09

sagar


1 Answers

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

----> is this correct??

Yes it is. You could also do it like this:

obj.test = Test(10);
like image 66
emlai Avatar answered Sep 02 '25 19:09

emlai