【问题标题】:inherit constructor from template-dependent base class从依赖模板的基类继承构造函数
【发布时间】:2021-07-26 20:23:08
【问题描述】:

如果基类的名称依赖于(派生类的)模板参数,我如何继承基类的构造函数?

例子:

#include <type_traits>

struct A {
};

struct B {
};

template <bool Abase>
struct C : public std::conditional_t<Abase, A, B> {
    using std::conditional_t<Abase, A, B>::(std::conditional_t<Abase, A, B>); // Error!
}

int main()
{
    C<true> c;
    C<false> c2;
}

在程序中struct C应该继承A::AB::B,取决于模板参数bool Abase的值。 编写的程序无法编译。

正确的语法是什么?

【问题讨论】:

  • using std::conditional_t&lt;Abase, A, B&gt;::conditional_t; 有效(并且是standard),虽然它很奇怪。

标签: c++ templates inheritance


【解决方案1】:

你可以先定义一个类型别名。

template <bool Abase>
struct C : public std::conditional_t<Abase, A, B> {
    using base = std::conditional_t<Abase, A, B>;
    using base::base;
};

LIVE

【讨论】:

    猜你喜欢
    • 2016-03-04
    • 2019-12-14
    • 2013-03-25
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多