【问题标题】:Using template base class template constructor in derived class在派生类中使用模板基类模板构造函数
【发布时间】:2021-07-13 19:35:11
【问题描述】:

我知道您可以在派生类中使用来自基类的构造函数,例如

class A {
public:
    A() {};
}

class B : public A {
public:
    using A::A;
}

此外,您可以使用模板基类中的构造函数,例如

template<typename T>
class A {
public:
    A() {};
}

template<typename T>
class B : public A<T> {
public:
    using A<T>::A;
}

假设类 A 现在有一个模板函数作为构造函数:

template<typename T1>
class A {
public:
    template<typename T2>
    A() {};
}

template<typename T1>
class B : public A<T1> {
public:
    using A<T1>::A;                           // nope
    using A<T1>::A<>;                         // neither             
    template<typename T2> using A<T1>::A<T2>; // sounds good, doesn't work

}

如何在派生类中使用基类构造函数?

【问题讨论】:

  • 你会怎么称呼那个构造函数?

标签: c++ inheritance


【解决方案1】:

两件事:

  • template&lt;typename T2&gt; A() {} 不能用作构造函数,因为无法推断出 T2。
  • 您一次只能继承所有构造函数。您不能选择特定的。

除此之外,using A&lt;T1&gt;::A; 是正确的。

【讨论】:

  • 你说得对,我在最后一个代码 sn-p 中编辑了构造函数的签名,以便可以推导出 T2。嗯,这比我想象的要容易。当然,我的更复杂的代码还有另一个问题,用这个最小的样本测试了你的答案,它运行良好!谢谢:)
  • @syntaxerror147 不客气!通常不鼓励在得到答案后对问题进行重大更改,以免让未来的读者感到困惑。所以我已经回滚了问题编辑,希望你不介意。
猜你喜欢
  • 1970-01-01
  • 2014-09-23
  • 2021-04-20
  • 2021-08-09
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-26
相关资源
最近更新 更多