Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally construct a `boost::optional` member variable on class constructor member initializer list

Tags:

c++

Suppose I have a non-copyable and non-moveable class Person:

struct Person
{
  int m_icNum;

  explicit Person(int icNum) : m_icNum(icNum) {}
  Person (const Person & other) = delete;
  Person (Person && other) = delete;
};

And another class PersonContainer:

struct PersonContainer
{
  boost::optional<Person> m_person;

  explicit PersonContainer(int icNum)
  : m_person( icNum >= 0 ? Person(icNum) : boost::none) // this does not compile because the two operands of ternary operator ? must have the same type
  {}
};

Apparently I cannot construct m_person using ternary expression in the initializer list. An alternative is to construct it in the ctor body using boost::in_pace, but I wonder if there is a nice way to construct it in the initializer list.

like image 954
Danqi Wang Avatar asked Dec 28 '25 04:12

Danqi Wang


1 Answers

Inspired by @kabanus' comment, this can be achieved using boost::in_place_init_if:

struct PersonContainer
{
  boost::optional<Person> m_person;

  explicit PersonContainer(int icNum)
  : m_person(boost::in_place_init_if, icNum >= 0, icNum)
  {}
};
like image 174
Danqi Wang Avatar answered Dec 30 '25 19:12

Danqi Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!