0

I am trying to inherit a "derived" class from either base1 or base2. I want to use template specialization for this purpose. I have the following

//base1
template<typename FT>
class base1
{
 public:
 base1(FT m)
 {}
};

//base2
template<typename FT>
class base2
{
  public:
  base2(FT m)
  {}
};

//define template specializations
template<int sType, typename FT>
class baseT {};

//for base1
template<typename FT>
class baseT<1,FT>
{
  public:
  typedef base1<FT> bType;
};

//for base2
template<typename FT>
class baseT<2,FT>
{
  public:
  typedef base2<FT> bType;
};

//Derived class which inherits either from base1 or base2
template<int sType, typename FT>
class derived : public baseT<sType,FT>::bType
{
  public:
  derived(FT m)
  {}
};

int main( )
{
  derived<1,float> a1(1);

  return 0;
}

This code is not compiling (on Linux platform) because the base class expects one argument but I am not sure how to pass it to the constructor of derived to make this work. (I dont want to use conditional). Any advice will help

Maxpm
  • 24,113
  • 33
  • 111
  • 170
  • I don't think the problem is in the code you posted. I've just compiled, not linked, the code sample that you posted and everything worked as expected – Radu Diță Jul 01 '15 at 21:12

1 Answers1

0
//Derived class which inherits either from base1 or base2
template<int sType, typename FT>
class derived : public baseT<sType,FT>::bType
{
  public:
  derived(FT m) : baseT<sType,FT>::bType(m)
  {}
};

That's all you need to make it work. Initialize the base class.

ikrabbe
  • 1,909
  • 12
  • 25
  • Thank you for the solution. I have another question - what if base1 and base2 have different number of constructor arguments, for example: base2(FT n1, FT n2){} is the constructor. Can the derived class still invoke either the base1 or base2 constructor? – Indranil Chowdhury Jul 02 '15 at 13:27
  • Obviously the template would not match either the one or the other base class. You see that you should use custom arguments for constructors with care! Often it is best to make constructor arguments optional. You could for example, replace the constructor with an init function and call that inside of the derived constructor function. – ikrabbe Jul 02 '15 at 14:39