首页 > 解决方案 > 将子类复制到父类,而父类有其他构造函数

问题描述

我在复制struct astruct b. 如果我删除我自己制作的构造函数,它会编译。我缺少什么构造函数来复制构造?

#include <array>

using f_t = float;

struct a {
    f_t x;
    a() : x(0) {}
};

struct b : public a, public std::array<f_t, 2> {

    b() {}

    b(const a& a_) : a(a_) {}

    b(a&& a_) : a(std::move(a_)) {}

    template <typename ...T>
    b(const T&... list) : std::array<f_t, 2>{list...} {}

    template <typename ...T>
    b(T&&... list) : std::array<f_t, 2>{(f_t)std::move(list)...} {}

};

int main() {
    a x;
    b y = x;

    return 0;
}

标签: c++inheritance

解决方案


我通过使用解决了这个问题concept

#include <array>

using f_t = float;

struct a {
    f_t x;
    a() : x(0) {}
};

template <typename T>
concept a_t = std::is_same<T, f_t>::value;

struct b : public a, public std::array<f_t, 2> {

    b() {}

    b(const a& a_) : a(a_) {}

    b(a&& a_) : a(std::move(a_)) {}

    template <a_t ...T>
    b(const T&... list) : std::array<f_t, 2>{list...} {}

    template <a_t ...T>
    b(T&&... list) : std::array<f_t, 2>{(f_t)std::move(list)...} {}

};

int main() {
    a x;
    b y = x;

    return 0;
}

推荐阅读