开发者

Meta-programming problem with Enums

Atm i have sth like that:

template<int n>
struct Pow
{
  enum{val= Pow<n-1>::val<<1};
};
template&开发者_JAVA百科lt;>
struct Pow<0>{
    enum{val =1};
};

I can acess data like Pow<30>::val. It's good but i want do like this

   int main()
    {
    Pow<30>::val;

and then use variable to access all of value <0,30> I knew that i can use array and dynamic programming but can i do that in this way? Sorry for English.


Using C++0x variadic templates:

template<int... Indices>
struct powers {
    static const int value[sizeof...(Indices)];

    typedef powers<Indices..., sizeof...(Indices)> next;
};

template<int... Indices>
const int powers<Indices...>::value[sizeof...(Indices)] = { Pow<Indices>::val... };

template<int N>
struct build_powers {
    typedef typename build_powers<N - 1>::type::next type;
};

template<>
struct build_powers<1> {
    typedef powers<0> type;
};

and then:

int
main()
{
    // we want [0..30] inclusive so pass 31 as exclusive upper limit
    typedef build_powers<31>::type power_type;
    // 0..30 is 31 powers in all
    typedef const int array_type[31];

    array_type& ref = power_type::value;
    // ref[0] .. ref[30] are the values of Pow<0>::val .. Pow<30>::val
}

So that's with using an array but without dynamic initialization. Since you want the result as a variable and not for TMP I feel this is adequate.


When you do Pow<30>::val; you will instantiate the top of your two templates, then when it get's to zero it will instantiate the specialization, and only the final result will be visible at runtime, since templates are resolved at compile time

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜