C ++:将数组/向量整数元素转换为constexpr

问题描述

为此,我真的无法在任何地方在线找到解决方案。我有点像C ++ 11之前的恐龙,而且我想不出是constexpr的类型转换。

有人知道如何将C样式的数组和/或std::vector(整数)元素转换为constexpr吗?

这就是说

int a[]={1,2};
vector<int> v={1,2};

我如何将a[1]v[1]转换为constexpr

constexpr int b=a[1];

例如,编译器会在for循环中抱怨。

error: the value of ‘a’ is not usable in a constant expression
     constexpr int b=a[i];

暂时我几乎没有想法。谢谢

解决方法

建议:如果可以使用至少C ++ 14而不是std::vector,则可以, 使用std::array

声明为constexpr

#include <array>

int main () 
 {
   constexpr std::array<int,2u> a {1,2};

   constexpr auto b = a[1];
 }

std::array是与constexpr兼容的类型,因此它是operator[]()const版本),或者是at()方法(const版本)。

C ++ 14是必需的,因为在C ++ 11中std::array::operator[]() conststd::array::at() const不是constexpr方法,因此不能在常量表达式中使用。

不幸的是,std::vector需要分配内存,因此(在C ++ 20之前)与constexpr不兼容。

对于C样式的数组,只需声明constexpr

int main () 
 {
// VVVVVVVVV   
   constexpr int a[] = {1,2};

   constexpr auto b = a[1];
 }
,

constexpr必须具有一个常量表达式,即必须在编译时知道它们。您无法使用b执行对a的赋值,在这种情况下是错误的。

在给定的代码片段中,a没有定义为constexpr,因此,它没有明确告诉编译器该表达式是常量。