Dheinamar
Dheinamar

Reputation: 15

const_cast on a static array to add constness

I've faced need to pass non-const static array to const argument. As I've discovered, const_cast may be used not only to remove, but also to add constness to type. So here's over-simplified version of what I'm trying to do:

int a[3] = { 1, 2, 3 };
const int b[3] = const_cast<const int[3]&>( a );

However it seems that compiler is unable to parse this with errors like

5:43: error: expected '>' before '&' token
5:43: error: expected '(' before '&' token
5:44: error: expected primary-expression before '>' token
5:50: error: expected ')' before ';' token

I've also tried to cast using pointers but got the same mistakes. Besides I don't want to switch to pointers as it would require to update quite big chunk of code.

It seems like relatively easy task, yet I'm already stuck on this for some time and wasn't able to find any useful info even remotely related to this topic.

UPD:

Thanks to comments I've found out that root cause in my case was not related to const_cast. If anyone is interested I was trying to initialise vector with list of static arrays of different sizes which apparently is not possible.

However since it was unobvious syntax of reference to array that led me to ask a question, I'm going to accept answer that explains it.

Upvotes: 1

Views: 450

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41770

This is not the syntax of reference to arrays. It would be spelled like this:

int a[3] = {1, 2, 3};
const_cast<const int(&)[3]>(a);

But your array cannot be copied. You must have a reference to it or use std::array:

int a[3] = {1, 2, 3};
auto& b = const_cast<const int(&)[3]>(a);

// or use std::array

std::array a = {1, 2, 3};
auto const b = a;

Upvotes: 0

eerorika
eerorika

Reputation: 238391

Firstly, your syntax for reference-to-array is wrong. The correct form is const int (&)[3]. Secondly, an array cannot be initialised from another array. Thirdly, it is typically unnecessary to cast non-const to const because such conversion is implicit.

Simplest way to make a const copy of an array is to use a wrapper class for the array. The standard library provides a template for such wrapper: std::array. Example:

std::array a { 1, 2, 3 };
const std::array b = a;

Upvotes: 3

Related Questions