hououin kyouma
hououin kyouma

Reputation: 47

How to inherit template constructor that will not work with base class instances?

I have many derived classes from base. Those classes must inherit constructor from base, but that constructor should only work with derived or base class instances.

Base class example:

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
};

Derived classes example:

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&)
};

How to do such a thing?

Upvotes: 0

Views: 169

Answers (1)

Jarod42
Jarod42

Reputation: 217870

It seems you want CRTP instead of common base class to avoid to duplicate code:

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;
};

Upvotes: 1

Related Questions