1

我有一个抽象基类和一个以非常基本的方式实现它的类:

class base {
public:
    virtual ~base() = default;
    virtual void func() = 0;
}

class base_core : public base {
public:
    base_core(int);
    void func() override {}
}

template <typename T>
concept IsBaseCore = std::is_base_of_v<base_core, T>;

现在,我创建了一个可变参数继承并注意到一个奇怪的行为,我认为这是错误的:

class temp_inheritance {};

template <typename Base, typename ...Decorators>
struct base_if_not_exists {
    static constexpr bool value = sizeof...(Decorators);
    using type = typename std::conditional_t<value, temp_inheritance, Base>;
};

template <typename T, IsBaseCore ...Cores>
class base_impl : virtual public base_if_not_exists<base_core, Cores...>::type, virtual public Cores... {
public:
    base_impl() : Cores(5)... {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        std::cout << "base_impl: Default CTOR" << std::endl;
    }

    base_impl(int num) : Cores(num)... {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        std::cout << "base_impl: Non default CTOR" << std::endl;
    }

    void func() override { std::cout << "base_impl::func(): " << param << std::endl; }

private:
    T param;
};

template <IsBaseCore ...Cores>
using impl_1 = base_impl<int, Cores...>;

template <IsBaseCore ...Cores>
using impl_2 = base_impl<double, Cores...>;

template <IsBaseCore ...Cores>
using impl_3 = base_impl<size_t, impl_1<impl_2<>>>;

int main() {
    impl_3<> impl(5);
    return EXIT_SUCCESS;
}

由于某种原因,这会输出以下结果:

base_core: Default CTOR
base_impl<T, Cores>::base_impl() [with T = double; Cores = {}]
base_impl: Default CTOR
base_impl<T, Cores>::base_impl(int) [with T = int; Cores = {base_impl<double>}]
base_impl: Non default CTOR
base_impl<T, Cores>::base_impl(int) [with T = long unsigned int; Cores = {base_impl<int, base_impl<double> >}]
base_impl: Non default CTOR

在此输出中,我有两点不清楚:

  1. 为什么会调用 base_core 默认构造函数?
  2. 为什么 impl_2 的参数化构造函数永远不会被调用?

我正在使用 Ubuntu 16.04(也在 20.04 上测试过),GCC 10.2。

4

0 回答 0