C 编译时间数组大小从模板函数

C++ compile time array size from template function

本文关键字:函数 编译 时间 数组      更新时间:2023-10-16

我不确定为什么函数中的数组创建会通过,而不是类中的数组创建,即使数组大小是compile compile time可计算值。

template<int N>
int getPow()
{
     int power = 1;
     while(power < N)
         power <<= 1;
     return power;
}
template<int N>
class Test
{
    private:
        int data[getPow<N>()];
};
void testfun()
{
    int test[getPow<2>()]; // passes
    Test<10> t1; // Fails????
}

as getPow不是 constexpr,不能在需要恒定表达式的地方使用(如c-array size)。

int test[getPow<2>()]; // passes 。不幸的是,您使用VLA扩展名。它不应该通过。

您可以通过以下方式解决您的问题:

template <unsigned N>
constexpr unsigned getPow()
{
     return 1 << N;
}