Suppose I have a template expression that contains an arrangement of types, in which case they are from an Abstract syntax tree :
template <typename... Children>
struct Branch
{
};
template <int param>
struct Leaf
{
};
The input expression can be any nested combination of types Branchand Leaf, but to simplify it, I will create a linear AST containing one Leafwrapped Nlayer deep in the Branchtypes:
using Expression =
Branch<
Branch<
Leaf>>; // N = 2
For this question, I created a function that generates these expressions on the fly, so I can demonstrate the problem that I have with graphs. So, here is the function that I will use to generate my expressions:
template <int N, typename T = Leaf>
struct Nest
{
using type = typename Nest<N-1, Branch<T>>::type;
};
template <typename T>
struct Nest<0, T>
{
using type = T;
};
Live example for N = 25
, , / , , Nest. Nest, , .
, , Branch?
, N == 2, , :
std::tuple<
Branch<Branch<Leaf>>,
Branch<Leaf>>;
, , , boost::mpl , , Boost 1.56. .
:
namespace detail
{
template <typename... T> struct Types {};
template <typename T, typename Enabled = void>
struct UnfoldImpl;
template <template <typename...> class Branch, typename... Children>
struct UnfoldImpl<
Types<Branch<Children...>>,
typename std::enable_if<Branch<Children...>::IsBranch::value>::type>
{
using type = typename TupleCat<
std::tuple<Types<Branch<Children...>>>,
typename UnfoldImpl<Types<Children...>>::type>::type;
};
template <typename Leaf>
struct UnfoldImpl<
Types<Leaf>,
typename std::enable_if<!Leaf::IsBranch::value>::type>
{
using type = std::tuple<>;
};
template <typename FirstBranch, typename... OtherBranches>
struct UnfoldImpl<Types<FirstBranch, OtherBranches...>,typename std::enable_if<sizeof...(OtherBranches)>::type>
{
using type = typename TupleCat<
typename UnfoldImpl<Types<FirstBranch>>::type,
typename UnfoldImpl<Types<OtherBranches...>>::type>::type;
};
}
template <typename Expression>
struct Unfold : detail::UnfoldImpl<detail::Types<Expression>> {};
, , , .
Unfold , , , . GCC 4.9.1 std=c++11, time -v g++ -std=c++11 main.cpp:

( time -v gcc ...) (.. Nest<N>::type main()), Unfold<Expression>::type, Expression - Nest<N>.
, , , , , . , , , - , Nlog(N) .
: Unfold - , O (N ^ 2)?
( ?), .