首页 文章

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

提问于
浏览
2

请考虑以下类型定义:

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;
                      ^~~ */

How can I add const to a typedef'ed array reference?

1 回答

  • 1

    您不能简单地将 const 添加到typedefed类型引用的类型 . 考虑typedefing指针类型:

    typedef int* pint_t;
    

    类型 const pint_t 命名一个指向可修改 int 的不可修改的指针 .

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

    typedef const int (&foo_t)[3];
    

    要么

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

    如果这是不可能的,那么制作最内部类型 const 的一般拆包方案可能是可实现的,但可能不可取 - 即检查您的设计 .

相关问题