constexpr函数作为数组大小 [英] constexpr function as array size

查看:142
本文介绍了constexpr函数作为数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我的代码编译,而不应该:

I'm trying to figure out why my code compiles, when it shouldn't:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

constexpr int ret_one()
{ 
    return 1;
}
constexpr int f(int p) 
{  
  return ret_one() * p; 
}

int main() {
    int i = 2;
    srand(time(0));
    int j = rand();
    int first_array[f(10)];     // OK - 10 is a constant expression
    int second_array[f(j)];     // Error - the parameter is not a constant expression
    j = f(i);                   // OK - doesn't need to be constexpr

    std::cout << sizeof(second_array);
    return 0;
}

因此 first_array 定义是好的。
但是因为 j 不是常量表达式,所以 second_array 定义应该是错误的。在每个程序运行我得到不同的数组大小。这是它应该如何工作?在我的书中,作者清楚地说,constepxr是一个表达式,其值可以在编译时评估。可以在编译时评估 rand()吗?我认为它不能。

So the first_array definition is OK. But because j is not a constant expression, the second_array definition should be wrong. On each program run I'm getting different array sizes. Is that how it's supposed to work? In my book the author clearly states that a constepxr is an expression whose value can be evaluated at compile time. Can rand() be evaluated at compile time? I think it can't be.

推荐答案

一些编译器,如GCC,允许C风格的可变长度数组扩展到C ++。

Some compilers, such as GCC, allow C-style variable-length arrays as an extension to C++. If your compiler does that, then your code will compile.

如果你使用GCC,那么你可以使用 -Wvla -pedantic

If you're using GCC, then you can enable a warning with -Wvla or -pedantic.

这篇关于constexpr函数作为数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆