Sj L
Sj L

Reputation: 41

C++: cast array/vector integer element to constexpr

I couldn't really find a solution online anywhere for this. I am a bit of a dinosaur from before C++11 and I couldn't figure out typecasting a constexpr.

Does anyone know how to convert a C-style array and/or a std::vector (integer) element into a constexpr?

That is to say, let's say

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

how would I convert a[1] and v[1] into constexpr?

constexpr int b=a[1];

for example, a compiler would complain in a for loop.

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

I am pretty much out of ideas for the time being. Thanks

Upvotes: 0

Views: 732

Answers (2)

Rohan Bari
Rohan Bari

Reputation: 7726

The constexpr must have a constant expression, i.e. they must be known at compile time. You can't perform an assignment to b with a, it's an error in this case.

In the given code snippet, the a isn't defined as constexpr, thus, it doesn't explicitly tells the compiler that the expression is a constant.

Upvotes: 0

max66
max66

Reputation: 66230

Suggestion: if you can use at least C++14, instead of std::vector, if you can, use a std::array

Declaring it constexpr

#include <array>

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

   constexpr auto b = a[1];
 }

std::array is a type compatible with constexpr and so it's operator[]() (const version), or also it's at() method (const version).

C++14 is required because in C++11 std::array::operator[]() const and std::array::at() const aren't constexpr methods so can't be used in a constant expression.

Unfortunately, std::vector require memory allocation so isn't compatible (before C++20) with constexpr.

For the C-style array case, you have only to declare it constexpr

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

   constexpr auto b = a[1];
 }

Upvotes: 3

Related Questions