5

如果X将以下代码转换为使用 C++11 可变参数模板,并且应该支持任意数量的模板参数,它会是什么样子?

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;
}
4

2 回答 2

3

也许:

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...>
{};

我希望我的语义是正确的。

于 2012-01-07T10:13:05.210 回答
0

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

于 2016-07-05T19:59:53.920 回答