mikejsavage.co.uk / blog

RSS feed

26 Dec 2019 / C++ tricks: compound literals

C99 has this nice thing where you can initialise structs inline with named members, so like:

struct A { int a, b, c; };

...

struct A a = ( struct A ) { .c = 1, .a = 2 };
printf( "%d %d %d\n", a.a, a.b, a.c ); // { 2, 0, 1 }

It’s useful so it’s not available in C++, but we can hack it together with variadic templates and pointer-to-members:

template< typename T >
T compound_literal() {
        return T();
}

template< typename T, typename A, typename... Rest >
T compound_literal( A ( T::* m ), const A & v, const Rest & ... rest ) {
        T t = compound_literal< T >( rest... );
        t.*m = v;
        return t;
}

...

A a = compound_literal< A >( &A::c, 1, &A::a, 2 );

I assume this breaks under even minimal C++ feature usage and the errors are the worst shit of my life but this post is a joke and you shouldn’t use it anyway.