将变量转换为const

时间:2011-12-08 10:18:46

标签: c++ boost constants

我有一个阵列,直到运行时才知道它的大小。程序启动并计算大小后,大小不会改变。

我测试了以下代码:

#include <iostream>
#include <boost/array.hpp>
#include <cstdint>

int main()
{

    uint32_t num_bits = 12;
    const uint32_t num_elements = 1 << num_bits;

    boost::array<double, num_elements > myArray; //does not work

    return 0;

}

自计算num_elements以来,以下代码无效。我看到有“const_cast”选项,但我不确定它是否能解决我的问题。

如果有一个增强解决方案,我会发表意见,因为我想使用boost :: array。

修改 num_bits是我从文件中读取的参数,这在运行时之前也是未知的。我知道使用std :: vector的解决方案,但访问速度也很重要,因为我经常访问这些元素,我的模拟大约需要3天......目前我只使用数组(new和delete)

3 个答案:

答案 0 :(得分:4)

Boost数组适用于在编译时已知大小的数组。它的论点必须是常量表达式。

使用std :: vector或类似的容器。

虽然您的示例不需要在运行时计算:

const uint32_t num_bits = 12; // mark this const too
const uint32_t num_elements = 1 << num_bits;

boost::array<double, num_elements > myArray;

答案 1 :(得分:4)

您不能使用std::vector代替boost::array吗? std::vector的大小可以在运行时计算。

const_cast仅在运行时将变量转换为/ const,它不能用于在编译时创建常量boost::array(和新的C ++ 11 std::array)想要。

答案 2 :(得分:0)

任何template的参数应该是编译时常量(或类型)。如果在编译时知道num_bits,那么将它用作编译时常量:

boost::array<double, (1 << num_bits)> myArray; //ok

如果在编译时未知大小,则使用动态分配的数组或std::vector