3 ms·
> don't have infinite different copies of the int64_t type You can make some, though! Basically, the idea is to define a class template NoAlias<T, Tag> that c
by nhaehnle 1y ago
> don't have infinite different copies of the int64_t type
You can make some, though!
Basically, the idea is to define a class template NoAlias<T, Tag> that contains a single value of type T. Implement operators etc. to make the type useful in practice for working with the wrapped value. Type-based alias rules mean that an access to the value wrapped in NoAlias<int64_t, Tag1> can never alias a value wrapped in NoAlias<int64_t, Tag2>. (Tag1 and Tag2 can just be forward-declared structs that are never defined.)
One time, I even encountered a situation where this was mildly useful.
- smallnamespace 1y agoTypescript ecosystem calls these "branded types" (branded like cattle, presumably) which I found to be a good evocative name.
- saagarjha 1y agoOf course this is substantially less doable in C :(
- nhaehnle 1y agoFair point, yeah. The general concept should still apply, you could maybe wrap it in some macros, but it is going to be more awkward mostly because of the lack of operator overloading.
- dzaima 1y agoYeah, I meant specifically C in an ergonomic way with operators working on them and being passable to existing functions. Though wrapping in different structs doesn't seem to even make gcc & clang properly optimize utilizing the types as non-aliasing: https://godbolt.org/z/r1MT9W9db https://godbolt.org/z/r1MT9W9db. Clang just completely fails to do anything, but gcc somehow manages to reorder the load but not do the trivial part of constant-propagating afterwards..