[英]Conditionally construct a `boost::optional` member variable on class constructor member initializer list
Suppose I have a non-copyable and non-moveable class Person
:假设我有一个不可复制和不可移动的类
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
:另一个类
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.显然我无法在初始化列表中使用三元表达式构造
m_person
。 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.另一种方法是使用
boost::in_pace
在 ctor 主体中构造它,但我想知道是否有一种很好的方法可以在初始化列表中构造它。
Inspired by @kabanus' comment, this can be achieved using boost::in_place_init_if :受@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)
{}
};
You can explicitly specify the ternary operator return type to be boost::optional<Person>
.您可以将三元运算符的返回类型明确指定为
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.