Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance based on flags

I have several classes, say A,B, and C, and corresponding flags HAS_A=1, HAS_B=2, and HAS_C=4. Is it possible to write a class in such a way that its parents (from A,B, and C) will be determined by a combination of these flags?

Example:

ParentsFromFlags<HAS_A | HAS_C> x;
// x ends up having the features of A and C

I know I can have variable multiple parents with <typename... Parents>, but I'd like this because I want to ensure that if A, B, and C are parents of the class, they will always appear in a certain order.

like image 249
Borislav Stanimirov Avatar asked Dec 10 '22 21:12

Borislav Stanimirov


1 Answers

This does the job, at the cost of introducing some extra class in the hierarcy...

enum ParentFlags { HAS_A = 1, HAS_B = 2, HAS_C = 4 };

class A{};
class B{};
class C{};

template <int M>
class ParentClass {};

template <>
class ParentClass<0>{};

template <>
class ParentClass<HAS_A> : public A {};

template <>
class ParentClass<HAS_B> : public B{};

template <>
class ParentClass<HAS_C> : public C{};

template <int F, int M>
class ParentTraits : public ParentClass<F & M>, 
                     public ParentTraits<F & ~M, M << 1>
{};

template <int M>
class ParentTraits<0, M>
{};

template <int F>
class ParentFromFlags : public ParentTraits<F, 1>
{
};

int main()
{
    ParentFromFlags<HAS_A | HAS_B> ab;
    ParentFromFlags<HAS_A | HAS_C> ac;
    ParentFromFlags<HAS_A | HAS_B | HAS_C> abc;
    return 0;
}
like image 104
marom Avatar answered Dec 13 '22 12:12

marom