简体   繁体   English

静态数组上的 const_cast 以添加常量

[英]const_cast on a static array to add constness

I've faced need to pass non-const static array to const argument.我面临需要将非常量静态数组传递给 const 参数的情况。 As I've discovered, const_cast may be used not only to remove, but also to add constness to type.正如我所发现的, const_cast 不仅可以用于删除,还可以用于为类型添加常量。 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.感谢评论,我发现在我的案例中的根本原因与 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.但是,由于引用数组的不明显语法导致我提出问题,因此我将接受解释它的答案。

Firstly, your syntax for reference-to-array is wrong.首先,您引用数组的语法是错误的。 The correct form is const int (&)[3] .正确的形式是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.第三,通常没有必要将非常量转换为 const,因为这种转换是隐式的。

Simplest way to make a const copy of an array is to use a wrapper class for the array.制作数组的 const 副本的最简单方法是使用数组的包装类。 The standard library provides a template for such wrapper: std::array .标准库为这样的包装器提供了一个模板: std::array Example:例子:

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

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 :您必须引用它或使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM