【问题标题】:How to inherit template constructor that will not work with base class instances?如何继承不适用于基类实例的模板构造函数?
【发布时间】:2020-04-18 16:50:37
【问题描述】:

我有 许多 从基类派生的类。这些类必须从基类继承构造函数,但该构造函数只能用于派生类或基类实例。

基类示例:

template<typename T, typename U>
struct bar
{ 
  bar() = default;

  template<typename _Bar_or_Derived>
  bar(const _Bar_or_Derived &); // must accept any bar or its derived classes
};

派生类示例:

template<typename T, typename U>
struct foo : public bar<T, U>
{ 
  using bar<T, U>::bar; 

 // must inherit something like foo(const Foo_or_Bar&)
};

template<typename T, typename U>
struct not_foo : public bar<T, U>
{ 
  using bar<T, U>::bar; 

 // must inherit something like not_foo(const NotFoo_or_Bar&)
};

这样的事情怎么办?

【问题讨论】:

  • 继承似乎是一个孤注一掷的命题。要么继承构造函数,要么不继承构造函数。如果构造函数是模板,则要么继承模板,要么不继承模板。如果您不介意显式包装器,则可以手动声明带有可变参数的派生类构造函数,该构造函数将其参数从基类转发到实例化的模板构造函数。这可能是这里能做的最多的事情了。
  • 但这将允许使用派生构造基类,不是吗?你能提供一些示例代码吗?
  • 当然,因为 C++ 就是这样工作的,除非派生类私下继承基类。
  • 听起来像XY problem。为什么你觉得有必要阻止构造函数接受派生类的实例?您要解决的最终问题是什么?
  • 您想要某种 CRTP 吗?定义bar(const foo&lt;_T, _U&gt;&amp;)?

标签: c++ templates inheritance metaprogramming template-meta-programming


【解决方案1】:

您似乎想要CRTP而不是通用基类以避免重复代码:

template <typename > struct Bar;
template <template <typename, typename> class C, typename T1, typename T2>
struct Bar<C<T1, T2>>
{
     Bar(const Bar&) {/*..*/}

     template <typename U1, U2>
     Bar(const Bar<C<U1, U2>>&) {/*..*/}

     template <typename U1, U2>
     Bar(const C<U1, U2>&) {/*..*/}
};
// Maybe you just need template <template <typename, typename> class C> struct Bar{};
// instead, as T1, T2 seems not used

template<typename T, typename U>
struct foo : public bar<foo>
{ 
    using bar<foo>::bar;
};

template<typename T, typename U>
struct not_foo : public bar<not_foo>
{ 
  using bar<not_foo>::bar;
};

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 2021-04-20
    • 2019-12-14
    • 2021-07-26
    • 2013-03-25
    • 1970-01-01
    • 2016-03-04
    • 2011-11-15
    相关资源
    最近更新 更多