简体   繁体   English

不可复制基的聚合初始化 class

[英]Aggregate initialization of noncopyable base class

I am constructing derived class from non-copyable base class. I would like to aggregate-initialize Base in the initializer:我正在从不可复制的基数 class 构造派生的 class。我想在初始化程序中聚合初始化Base

// for convenience, could be any other way to disable copy
#include<boost/noncopyable.hpp>
struct Base: public boost::noncopyable{
    int a;
};
struct Derived: public Base{
    Derived(int a): Base{a} {}
};

but I am getting:但我得到:

error: could not convert ‘a’ from ‘int’ to ‘boost::noncopyable_::noncopyable’

As I understand, noncopyable cannot be initialized, fair enough.据我了解, noncopyable无法初始化,这很公平。 Can I then somehow craft the aggregate initializer so that noncopyable initialization is skipped?然后我可以以某种方式设计聚合初始化器以便跳过不可复制的初始化吗? (I tried eg things like Base{{},a} without real understanding, but that did not work either: ~noncopyable is protected). (我在没有真正理解的情况下尝试了诸如Base{{},a}之类的东西,但这也没有用: ~noncopyable是受保护的)。

Or will I need to explicitly define Base::Base which will skip the noncopyable initialization, using it from Derived::Derived instead of the aggregate initialization?或者我是否需要显式定义Base::Base来跳过noncopyable的初始化,使用它从Derived::Derived而不是聚合初始化?

The aggregate initialization of the base class you tried你试过的base class的聚合初始化

Derived(int a): Base{{}, a} {}
//                   ^^ 

Would have worked if the constructor of boost::noncopyable wasn't protected (see here ).如果boost::noncopyable的构造函数未受protected (请参阅此处),将会起作用。

The easiest fix should be to add a constructor to the base class.最简单的修复方法应该是向基类 class 添加一个构造函数。

#include <boost/core/noncopyable.hpp>

struct Base: private boost::noncopyable
{
    int a;
    Base(int a_) : a{a_} {}
};

struct Derived: public Base
{
    Derived(int a): Base{a} {}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM