我可以将optional :: emplace称为成员初始值设定项吗? [英] Can I call optional::emplace as a member initializer?

查看:57
本文介绍了我可以将optional :: emplace称为成员初始值设定项吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在现有的类中添加新的构造函数,并想知道是否可以以某种方式对可选 emplace 初始化。 c $ c>,然后在初始化器中将该值用于另一个成员值。

I'm trying to add a new constructor an existing class and wondering if I can somehow do an emplace initialization of an optional and then use that value in the initializer for another member value.

例如:

class sample {
    my_type sc;
    optional<opt_type> run;

    sample() :
        sc( gen_default() ) {
    }

    enum ctor_alt { ctor_alt };
    sample( ctor_alt ) :
        emplace( run, ctor_arg ), /* Possible somehow? */
        sc( run.field ) {
    }

我的主要动机是我不想更改 my_type 的类型。这个变量有很多用户,将其放入包装中将需要更改大量代码。

My primary motivation is that I don't want to alter the type of my_type. There are many users of this variable and putting it in a wrapper would require changing a lot of code.

推荐答案

当然,呼叫 std :: optional 构造函数$ c> 与 std :: in_place_t

Sure thing, just call the constructor of std::optional with std::in_place_t:

run{std::in_place, ctor_arg}

std :: in_place_t 是一种标签类型,可在您希望使用该类型时对其进行消歧

std::in_place_t is a tag type to disambiguate when you want the type to construct the value in place instead of copying it.

如果要对另一个成员变量使用optional的值,则需要确保该成员变量 之后是可选的,因为成员对象是按照它们出现的顺序初始化的。

If you want to use the value of the optional for another member variable, you need to make sure that that member variable comes after the optional, because member objects are initialized in the order that they appear.

这篇关于我可以将optional :: emplace称为成员初始值设定项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆