首页 > 解决方案 > 如何继承不适用于基类实例的模板构造函数?

问题描述

我有很多来自基类的派生类。这些类必须从基类继承构造函数,但该构造函数只能与派生类或基类实例一起使用。

基类示例:

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++templatesinheritancemetaprogrammingtemplate-meta-programming

解决方案


似乎您想要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;
};

推荐阅读