Home > Net >  Finding nearest "ancestor" in tree of types
Finding nearest "ancestor" in tree of types

Time:10-20

I am forming a "tree" of types in the following way:

template <typename T, typename PARENT, typename ... CHILDREN>
class Node {};

class X;
class A;
class AA;
class AB;
class B;
class BA;
class BB;

class X : public Node<X, void, A, B> {};

class A : public Node<A, X, AA, AB> {};
class AA : public Node<AA, A> {};
class AB : public Node<AB, A> {};

class B : public Node<B, X, BA, BB> {};
class BA : public Node<BA, B> {};
class BB : public Node<BB, B> {};

I need to write a "traits" type such that I can get the "nearest ancestor" given CHILDREN... and PARENT from within the Node base class. For example

nearest_ancestor<X, BB>::type should be B (because B is the next accessible leaf from X "on the way to" BB)

Please let me know if what I am asking doesn't make sense.

CodePudding user response:

I think I figured it out.

Assuming the Node base class has the following:

template <typename T, typename PARENT, typename ... CHILDREN>
class Node {
    using parent_type = PARENT;
};

Then nearest_ancestor can be defined as:

template <typename T, typename U, typename ENABLE = void>
struct nearest_ancestor {
    using type = typename nearest_ancestor<T, typename U::parent_type>::type;
};

template <typename T, typename U>
struct nearest_ancestor<T, U, std::enable_if_t<std::is_same_v<T, typename U::parent_type>>> {
    using type = U;
};
  • Related