Sujet : Re: constexpr keyword is unnecessary
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 29. Oct 2024, 15:13:16
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vfqqhs$1j1i2$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 29/10/2024 13:21, Thiago Adams wrote:
On 29/10/2024 09:16, Thiago Adams wrote:
Edit to fix the sample
// Here we acknowledge the truncation
void f(int i) {
...
const unsigned char c = i; [[!truncation]];
}
// Warning: there is no truncation to acknowledge.
void f(unsigned char i) {
...
const unsigned char c = i; [[!truncation]];
}
This should give you what you are asking for, if I have understood you correctly:
#define truncate(type, value) \
_Generic((value), \
type : (void) 0, \
default : (type) value \
)
// OK
void f1(int i) {
const auto c = truncate(unsigned char, i);
}
// Error
void f1(unsigned char i) {
const auto c = truncate(unsigned char, i);
}
I am not at all convinced this is a good idea. I am /certainly/ not convinced "truncate" is a good name - the general term, AFAIK, for a conversion that might try to squeeze a large value into a smaller type is "narrowing" rather than "truncating".
You could expand the idea further and have a "truncate" macro that checks for bounds at run time or compile time (I'd make use of the gcc extension __builtin_constant_p here, but there may be a fully standard way to do this).