将 const 限定符添加到数组引用 typedef

Add const qualifier to array reference typedef

考虑以下类型定义:

typedef int (&foo_t)[3];

using foo_t = int(&)[3];

在类型中添加const限定符时,被忽略:

int foo[3] = {1, 2, 3};
const foo_t fooref = foo;
fooref[0] = 4;  // No error here

或者当我尝试为其分配一个 const 数组时:

const int foo[3] = {1, 2, 3};
const foo_t fooref = foo;
/* error: binding reference of type ‘foo_t’ {aka ‘int (&)[3]’} to ‘const int [3]’ discards qualifiers
 const foo_t fooref = foo;
                      ^~~ */

如何将 const 添加到 typedef 数组引用中?

您不能简单地将 const 添加到类型定义类型引用的类型。考虑对指针类型进行类型定义:

typedef int* pint_t;

类型 const pint_t 将不可修改的指针命名为可修改的 int

如果可以,只需将其添加到定义中(或定义类型的 const 变体):

typedef const int (&foo_t)[3];

using foo_t = const int(&)[3];

如果这是不可能的,一个通用的解包方案来制作最内层的类型 const 可能是可行的,但可能不可取 - 即检查你的设计。