Inheritance using template?

I am not sure how to solve this issue but I am sure other people had a similar situation before.

I have a Base class (could be abstract).
I have 2 classes that inherit from the Base class (Derived1 and Derived2).
I have a 3rd class that inherits from the Base class using the implementation from Derived1 or Derived2 (it depends of the instance).

I though that maybe I could use a template to achieve this?

Here is my test (it doesn't compile)

namespace {

class Base {
protected:
virtual int Test() = 0;
};

class Derived1: public Base {
protected:
virtual int Test() { return 1; }
};

class Derived2: public Base {
protected:
virtual int Test() { return 2; }
};

template<class T>
class DerivedMain: public T::Base {
public:
void Execute() {
int nTest = Test();
}
};
}

int main(int argc, char* argv[]) {
DerivedMain<Derived1> oInstance1;
DerivedMain<Derived2> oInstance2;

return 0;
}
I have a 3rd class that inherits from the Base class using the implementation from Derived1 or Derived2 (it depends [on] the instance).
This isn't worded so clearly because instances exist only at runtime, but inheritance exists at compile-time -- but I think I get what you mean.

There is no diamond problem because DerivedMain<T> instantiates a different class for each T.

Simply inherit from T:
1
2
3
4
template <typename T> 
class DerivedMain: public T { 
public: /* ... */
};


You will need to specify that you are calling your superclass' implementation of the pure virtual function Base::Test() in the code for DerivedMain. Such a call would look like T::Test();
Last edited on
Thanks, it works exactly as intended! My only "concern" is that I cannot force T to be a derived class of Base. Anyway to enforce that?
static_assert and some template metacode can do this. See std::is_base_of.

Are you sure that's not overly restrictive? I don't know if DerivedMain<T> needs to know about its grandparent.
Topic archived. No new replies allowed.