【问题标题】:Inheriting templated constructor from class template?从类模板继承模板化构造函数?
【发布时间】:2016-03-04 12:49:28
【问题描述】:

从 C++11 中的类模板继承构造函数(其中一些是模板)的语法是什么?

template <class T>
struct Base
{
    using type = T;
    explicit constexpr Base(const type& x): value{x} {};
    template <class U> explicit constexpr Base(U&& x): value{std::forward<U>(x)} {};
    type value;
}

struct Derived: Base<bool>
{
    using Base::Base<bool>; // Does not seem to work ?!?
}

【问题讨论】:

  • 试试using Base&lt;bool&gt;::Base;(我自己没试过,但我确定你需要&lt;bool&gt;::之前,只是不确定::之后的工作原理)
  • 你到底想做什么?如果您想要 Base bool 构造函数,那么您不需要模板化构造函数。然后你只需按照 JSF 的建议说 using Base&lt;bool&gt;::Base
  • 构造函数必须全部继承在一起,不能挑挑拣拣。 (但是,默认、复制和移动构造函数会被自动排除。)

标签: c++ templates c++11 inheritance constructor


【解决方案1】:

你派生自Base&lt;bool&gt;。所以你的基类是Base&lt;bool&gt;,继承构造函数是通过

using Base<bool>::Base;

Live on Coliru

:: 后面不需要Base&lt;bool&gt;,实际上你放了代码是不会编译的。构造函数仍称为Base,而不是Base&lt;bool&gt;。这与引用类模板的成员函数一致:您使用例如void Foo&lt;int&gt;::f() 而不是void Foo&lt;int&gt;::f&lt;int&gt;() 来引用Foo 的成员函数f()

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 2019-12-14
    • 1970-01-01
    • 2018-09-29
    • 2013-05-07
    • 2013-03-25
    • 2015-08-06
    • 2021-07-26
    相关资源
    最近更新 更多