Search code examples
c++structtypesconstantstype-declaration

Does c++ provide a way to make a whole struct constant (non-modifiable)?


So far, I know that I can make all the struct members const. But can I write somewhere const once and have all the members turned to const?

In other words, I want all the struct instances to be const even if I forgot to add const modifier in a variable declaration.

const struct Foo {}

The above doesn't work due to const can only be specified for objects and functions error;


Solution

  • While you can't make a whole type const you can make an alias to that type with a const qualifier.

    struct Foo {};
    using ConstFoo = const Foo;
    ConstFoo myFoo; // Same as const Foo myFoo;
    

    Here, ConstFoo acts as a type that is always const.

    If you'd rather keep Foo as a const type, you can use

    using Foo = const struct {};