gpt4 book ai didi

c++ - 是否可以使用模板元编程创建和初始化一组值?

转载 作者:IT老高 更新时间:2023-10-28 13:02:39 27 4
gpt4 key购买 nike

我希望能够在编译时使用模板元编程创建一个计算值数组(为了简单起见,我希望每个值都是它的索引的平方)。这可能吗?数组中的每个位置是如何初始化的?

(是的,有更简单的方法可以做到这一点,而无需借助模板元编程,只是想知道是否可以使用数组来做到这一点。)

最佳答案

在 c++0x 中可以使用可变参数模板。以下是如何创建二项式系数表的示例:

//typedefs used
typedef short int index_t;
typedef unsigned long long int int_t;

//standard recursive template for coefficient values, used as generator
template <index_t n, index_t k> struct coeff {static int_t const value = coeff<n-1, k-1>::value + coeff<n-1, k>::value;};
template <index_t n> struct coeff<n, 0> {static int_t const value = 1;};
template <index_t n> struct coeff<n, n> {static int_t const value = 1;};

//helper template, just converts its variadic arguments to array initializer list
template<int_t... values> struct int_ary {static int_t const value[sizeof...(values)];};
template<int_t... values> int_t const int_ary<values...>::value[] = {values...};

//decrement k, pile up variadic argument list using generator
template<index_t n, index_t k, int_t... values> struct rec: rec<n, k-1, coeff<n, k-1>::value, values...> {};
//when done (k == 0), derive from int_ary
template<index_t n, int_t... values> struct rec<n, 0, values...>: int_ary<values...> {};

//initialise recursion
template<index_t n> struct binomial: rec<n, n+1> {};

要访问元素,请使用二项式 ::value[k] 之类的语法,其中 N 是编译时间常数,k 是范围从 0 到 N 的索引。

关于c++ - 是否可以使用模板元编程创建和初始化一组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com