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

时间:2018-12-09 17:29:15

标签: c++ arrays const 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添加到类型定义的数组引用中?

1 个答案:

答案 0 :(得分:1)

您不能简单地将const添加到类型定义的类型所引用的类型。考虑一下定义指针类型的方法:

typedef int* pint_t;

类型const pint_t指向不可修改的int的指针。

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

typedef const int (&foo_t)[3];

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

如果这是不可能的,那么使最里面的类型const的通用拆包方案可以实现,但可能不建议-即检查设计。

相关问题