【问题标题】:Conditionally construct a `boost::optional` member variable on class constructor member initializer list有条件地在类构造函数成员初始值设定项列表上构造一个 `boost::optional` 成员变量
【发布时间】:2020-08-24 15:48:57
【问题描述】:

假设我有一个不可复制和不可移动的类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 主体中构造它,但我想知道是否有一种很好的方法可以在初始化列表中构造它。

【问题讨论】:

    标签: c++


    【解决方案1】:

    受@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)
      {}
    };
    

    【讨论】:

      【解决方案2】:

      您可以将三元运算符的返回类型显式指定为boost::optional&lt;Person&gt;

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

      【讨论】:

      • 在我的问题中Person 是不可复制和不可移动的
      • 您应该可以将它与in_place_init 结合使用,@Danqi : boost::optional&lt;Person&gt;(boost::in_place_init, icNum)
      • @kabanus 不错。实际上我发现甚至还有一个in_place_init_if 标签,这正是我所需要的。感谢指路:: m_person(boost::in_place_init_if, icNum &gt;= 0, icNum)
      • @Danqi,完美,我很陌生!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 2011-08-08
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多