簡體   English   中英

在類構造函數成員初始值設定項列表上有條件地構造一個 `boost::optional` 成員變量

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

假設我有一個不可復制和不可移動的類Person

struct Person
{
  int m_icNum;

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

另一個類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
  {}
};

顯然我無法在初始化列表中使用三元表達式構造m_person 另一種方法是使用boost::in_pace在 ctor 主體中構造它,但我想知道是否有一種很好的方法可以在初始化列表中構造它。

受@kabanus 評論的啟發,這可以使用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)
  {}
};

您可以將三元運算符的返回類型明確指定為boost::optional<Person>

explicit PersonContainer(int icNum)
  : m_person( icNum >= 0 ? boost::optional<Person>{Person(icNum)} : 
                           boost::optional<Person>{boost::none}) 
  {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM