There are tons of questions about the least common ancestor algorithm, but this one is different because I'm trying to determine the LCA at compile-time, and my tree is neither binary nor a search tree, even though my simplified version may look like one.
Suppose you have a bunch of structures which contain a member typedef parent
, which is another similar structure:
struct G
{
typedef G parent; // 'root' node has itself as parent
};
struct F
{
typedef G parent;
};
struct E
{
typedef G parent;
};
struct D
{
typedef F parent;
};
struct C
{
typedef F parent;
};
struct B
{
typedef E parent;
};
struct A
{
typedef E parent;
};
which together make a tree such as
A B C D
\ / \ /
E F
\ /
\ /
\ /
G
NOTE: There is no inheritance relationship between the structures.
What I would like to do is create a type-trait least_common_ancestor
such that:
least_common_ancestor<A, B>::type; // E
least_common_ancestor<C, D>::type; // F
least_common_ancestor<A, E>::type; // E
least_common_ancestor<A, F>::type; // G
What's the best way to do this?
I'm not concerned with algorithmic complexity particularly since the tree depth is small, rather I'm looking for the simplest meta-program that that will get to the correct answer.
EDIT: I need to be able to build the solution with msvc2013, among other compilers, so answers without constexpr
are preferred.
constexpr
. – Cafeteria