2

Consider the following type definition:

typedef int (&foo_t)[3];

or

using foo_t = int(&)[3];

When adding a const qualifier to the type, it is ignored:

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

Or when I try to assign a const array to it:

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 Answer 1

1

You cannot simply add a const to the type referenced by a typedefed type. Think of typedefing a pointer type:

typedef int* pint_t;

The type const pint_t names an unmodifiable pointer to a modifiable int.

If you can, simply add it to the definition (or define a const variant of your type):

typedef const int (&foo_t)[3];

or

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

If that's out of the question, a general unpacking scheme to make the inner-most type const may be implementable, but probably not advisable - i.e. check your design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.