Abseil C++

An open-source collection of C++ library code designed to augment the C++ standard library

  • Tip of the Week #172: Designated Initializers
    https://abseil.io/tips/172

    Originally posted as TotW #172 on December 11, 2019

    By Aaron Jacobs

    Updated 2020-04-06

    Quicklink: abseil.io/tips/172

    Designated initializers are a syntax in the draft C++20 standard for specifying the contents of a struct in a compact yet readable and maintainable manner. Instead of the repetitive

    struct Point double x; double y; double z; ;

    Point point; point.x = 3.0; point.y = 4.0; point.z = 5.0;

    one can use designated initializers to write

    Point point = .x = 3.0, .y = 4.0, .z = 5.0, ;

    This is a little less repetitive, but more importantly, can be used in more contexts. For example, it means the struct can be made const without resorting to awkward workarounds:

    // Make it clear to the reader (of the potentially complicated larger piece of // code) that this (...)