C++: is conditional inheritance possible
arduino, c++, inheritance
Solution
A much more clean solution would be using template : let the compiler choose the base class depending on a template argument.
Here is one example:
#include <type_traits> //for std::conditional
//here you go with your own class
template<bool UseAdvanced>
class Foo : public std::conditional<UseAdvanced, Advanced, Basic>::type
{
//your code
};
And here is how you would be using this class:
Foo<true> fooWithAdvanced; //it uses Advanced as base class
Foo<false> fooWithBasic; //it uses Basic as base class!
Well that is one way to do that. But there are better ways. In particular, I would design the class template in the following way, in which the template argument would act as base class. This would be more flexible design.
template<typename Base>
class Foo : public Base
{
//your code
};
So you can use `Basic`, `Advanced` or any other class as base class, as long as it supports the functionalities as required by `Foo` and its usage:
Foo<Advanced> fooWithAdvanced;
Foo<Basic> fooWithBasic;
Foo<OtherBase> fooWithOtherBase;
Hope that helps.
Problem
I'm working on a micro-processor(Arduino) project. My library `Foo` is inherited from a existing library `Basic`. Later I extended the functionalities of `Basic`, into another class `Advanced`. However, `Advanced` stretches the hardware harder, making one of the already made demos unusable. What I'm thinking about is as following: ``` class Foo: #ifndef USE_BASIC public Advanced #else public Basic #endif { ... } ``` And put `#define USE_BASIC` in my demo code: ``` #define USE_BASIC #include <Foo.h> ``` However Foo is not inheriting from Basic. Am I doing it wrong here? Or if there're alternatives to solve this problem?