Date: Sun, 7 Jun 2026 21:50:11 +0100
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<>.
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++.
#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<>.
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++.
Received on 2026-06-07 20:50:28
