2012-12-28 23 views
5

可能重复:
Programmatically create static arrays at compile time in C++如何初始化固定大小阵列和分配与constexpr功能元件C++ 11或升压的帮助

我有大量的数据以固定阵列存储,其元素取决于位置。每个元素的值可以在编译时计算。

我的代码几乎是像:

int fun(int p) // maybe constexpr 
{ 
    return 0x1<<p; 
} 

int a[17] = { 
    repeat_fun_from_0_to_16(); 
}; 

由于所有的值可以在编译时确定的,应该有办法做到这一点,我想。

我也检查了在boost.assignment中有一个repeat(),但不知道如何在这种情况下使用它。

+4

这http://stackoverflow.com/questions/12108390/c11-compile-time-calculation-of-array与此http:// stackoverflow.com/questions/2978259/programmatically-create-static-arrays-at-compile-time-in-c?lq=1可能会帮助 – 2012-12-28 12:02:06

+0

谢谢,@aleguna!我已经找到了第二个链接。 – liuyanghejerry

回答

1

感谢@aleguna,我已通过this answer解决了此问题。

所有我需要改变的是元函数:

template<size_t index> struct MetaFunc { 
    enum { value = index << 1 }; 
};