代码之家  ›  专栏  ›  技术社区  ›  smac89

重载继承的构造函数

  •  1
  • smac89  · 技术社区  · 6 年前

    class Base {
        int a, b;
    public:
        Base(int a, int b=42): a(a), b(b) { }
    };
    

    以及从基派生的类:

    class Derived: public Base {
        using Base::Base; // inherit Base constructors
        bool c;
    public:
        Derived(int a): Base(a), c(true) { }
        Derived(int a, int b): Base(a, b), c(true) { }
    };
    

    有没有一种方法可以避免创建两个单独的构造函数 Derived Base 构造函数初始化的额外成员 派生 ?

    template <typename... Args, 
        typename std::enable_if_t<std::is_constructible_v<Base, Args&&...>, int> = 0>
    explicit Derived(Args&&... args):
        Base(std::forward<Args>(args)...), c(true) {}
    

    这很接近,但过于冗长,如果继承了基类的构造函数,则不起作用。i、 e.如果 using Base::Base 在类中存在(然后它默认为那些构造函数,并且不初始化字段) b ).

    使用Base::Base .


    这是做这工作的唯一方法吗?i、 e.通过移除 使用Base::Base 在每个派生类中使用可变模板构造函数?有没有一种不那么冗长的方法来重载继承的构造函数?

    我使用C++ 17。

    2 回复  |  直到 6 年前
        1
  •  2
  •   NathanOliver    6 年前

    在这种情况下,您只需提供 c

    class Derived : public Base {
        using Base::Base;
        bool c = true;
    };
    

    允许您使用 Base 的构造函数并将初始化 true 在所有情况下。

        2
  •  2
  •   Barry    6 年前

    看来你要找的是继承遗产的方法 Base 的构造函数,而只是初始化 Derived

    class Derived: public Base {
    public:
        using Base::Base;
    private:
        bool c = true;
    };
    

    构建 Derived(42) 将调用 Base(int) 构造函数,还可以初始化 c true .