C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Achieving pragma pack(1) with typedef<unaligned>

From: Alejandro Colomar <une+cxx_std-proposals_at_[hidden]>
Date: Mon, 8 Jun 2026 02:11:50 +0200
Hi Frederick,

On 2026-06-07T21:50:11+0100, Frederick Virchanza Gotham via Std-Proposals wrote:
> Most people here will be familiar with:
>
> #pragma pack(1)
>
> struct J {
> int a;
> char b;
> int c;
> char d;
> int e;
> };
>
> #pragma pack()
>
> On most computers, this brings sizeof(J) down from 20 bytes to 14 bytes.
>
> I have an idea about how to standardise this. Firstly we need a new
> template class, "std::unaligned", which you can see defined here:
>
> https://github.com/healytpk/gcc-thomas-healy/blob/typedefangles/libstdc%2B%2B-v3/include/std/unaligned
>
> So the aforementioned struct could then be written as:
>
> struct J {
> unaligned<int > a;
> unaligned<char> b;
> unaligned<int > c;
> unaligned<char> d;
> unaligned<int > e;
> };
>
> But the above is a little tedious to write. That's why I suggest a new
> form of 'typedef' that's followed by angle brackets, and you can use
> it as follows:
>
> struct J {
> int a;
> char b;
> int c;
> char d;
> int e;
> };
>
> typedef< std::unaligned > J K;
>
> As you guessed, the struct K will be the struct J but with every
> member variable type enclosed in unaligned<>.

I didn't guess it.

Also, keeping a struct K that is not packed is going to be error prone.
One might use struct J thinking it's also packed.

Not a good idea.


Have a lovely night!
Alex

>
> You can put any class template you want in there, for example:
>
> typedef< std::optional > J K;
>
> Try out here up on GodBolt:
>
> https://godbolt.org/z/a8zoYavYE
>
> Personally I think this is the No. 1 best strategy proposed so far to
> add packed structs to standard C++.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

-- 
<https://www.alejandro-colomar.es>

Received on 2026-06-08 00:11:58