Allan
Allan

Reputation: 4730

Chaining variadic templates together

What would X in the following code look like if it was converted to use C++11 variadic templates, and should support arbitrary number of template arguments?

template<int OFFSET>
struct A { enum O { offset = OFFSET }; enum S { size = 2 }; };

template<int OFFSET>
struct B { enum O { offset = OFFSET }; enum S { size = 4 }; };

template<int OFFSET>
struct C { enum O { offset = OFFSET }; enum S { size = 10 }; };

template < template <int> class B0,
           template <int> class B1,
           template <int> class B2  >
struct X : public B0<1>,
                  B1<B0<1>::size * B0<1>::offset >,
                  B2< B1<B0<1>::size * B0<1>::offset >::size *
                      B1<B0<1>::size * B0<1>::offset >::offset >
{ };

int main(int argc, const char *argv[])
{
    X<A, B, C> x;
    return 0;
}

Upvotes: 5

Views: 258

Answers (2)

filmor
filmor

Reputation: 32298

Maybe:

template <int Var, template <int> Head, typename... Tail>
struct X_helper : Head<Var>,
                , X_helper<Head<Var>::size * Head<Var>::offset, Tail...>
{};

template <int Var, template <int> Arg>
struct X_helper : Head<Var>
{};

template <typename... Args>
struct X : X_helper<1, Args...>
{};

I hope I got the semantics right.

Upvotes: 3

max66
max66

Reputation: 66230

You're still interested in this question?

I'm plying with C++11 so I've tried to answer.

I'm not sure to understand what you want (well... what you wanted in 2012) but I think the following example should catch you're requirements.

template<int OFFSET>
struct A { enum O { offset = OFFSET }; enum S { size = 2 }; };

template<int OFFSET>
struct B { enum O { offset = OFFSET }; enum S { size = 4 }; };

template<int OFFSET>
struct C { enum O { offset = OFFSET }; enum S { size = 10 }; };

template <int N, template <int> class ...>
   struct H;

template <int N>
   struct H<N>
    { };

template <int N,
          template <int> class C1,
          template <int> class ... Cs>
   struct H<N, C1, Cs...> : public C1<N>,
                            public H<C1<N>::size * C1<N>::offset, Cs...>
    { };

template <template <int> class ... C>
   struct X : public H<1, C...>
    { };

int main()
 {
   X<A, B, C> x;

   return 0;
 }

p.s.: sorry for my bad English

Upvotes: 0

Related Questions