3 ms·
on a somewhat related note, I've always wished for something like `explicit` that prevents assigning different typedefs for the same underlying type to each oth
by leetcrew 6y ago
on a somewhat related note, I've always wished for something like `explicit` that prevents assigning different typedefs for the same underlying type to each other. like suppose I have two types, WorldVec (vector in worldspace) and ViewVec (vector in view/sceenspace). under the hood they are both typedefs for float[3], so I can freely assign them back and forth. but any vector operation that mixes the types would almost always be a bug, since they are in different spaces. would be cool to get this functionality out of the humble typedef.
- syrrim 6y agostructs
- Reelin 6y agoThis has always bugged me as well. I've generally solved this by wrapping things in a struct. Type checking will use the (incompatible) wrappers and a modern compiler should optimize them away. To avoid strict aliasing violations when converting between equivalent wrapped types you can use a union and employ a function to hide the verbosity. I have no idea if this is the "right" way to do things, but it seems to work.
- alternatetwo 6y agoThat's what Microsoft did from some version on in their build tools, all the HANDLE's etc used to just be typedef void , now they're a dummy struct each (HANDLE__ ). Seems to be a good solution.
- pjmlp 6y agoThat was already opt-in back in the Windows 3.1 days, but few bothered to use it as such. Back when I was doing pure Windows C for a while, this helped quite a bit, Basically you had to #include<windowsx.h> and define the STRICT macro. There were also several utilities that made it much easier to deal with events, dialogs and callbacks. https://docs.microsoft.com/en-us/windows/win32/api/windowsx/ https://docs.microsoft.com/en-us/windows/win32/api/windowsx/ https://jeffpar.github.io/kbarchive/kb/083/Q83456/ https://jeffpar.github.io/kbarchive/kb/083/Q83456/ I got to learn it via the "Programmer's introduction to Windows 3.1" book, https://archive.org/details/programmersintro00myer https://archive.org/details/programmersintro00myer
- ComputerGuru 6y agoC is considered strictly typed but that’s only when compared to the likes of JS, Python, and co. What you’re taking about is incredibly important and using it in other truly strongly typed languages has opened my eyes to just how much compile time safety a language can really provide, practically free of cost.
- account42 6y agoYou can do that in C++ by wrapping he type in a new class although it requires some boilerplate depending on which operators you want to support. [0] You don't have to use all features of C++ - if you prefer a more C like style you can have that. [0] https://www.boost.org/doc/libs/1_48_0/boost/strong_typedef.hpp https://www.boost.org/doc/libs/1_48_0/boost/strong_typedef.h...