Many libraries I have seen/used have typedefs to provide portable, fixed size variables, eg int8, uint8, int16, uint16, etc which will be the correct size regardless of platform (and c++11 does it itself with the header stdint.h)
After recently using binary file i/o in a small library I'm writing I can see the benefit of using typedefs in this way to ensure the code is portable.
However, if I'm going to the trouble of typing "namespace::uint32" rather than using built in fundamental types, I may as well make the replacement as useful as possible. Therefore I am considering using classes instead of simple typedefs.
These wrapper classes would implement all normal operators so could be used interchangeably with the fundamental type.
Eg:
int x = 0;
//do stuff
could become
class intWrapper {
//whatever
};
intWrapper = 0;
//do stuff
without having to modify any code in "//do stuff"
The reason I'm considering this approach as opposed to just typedefs is the fact I already have functions that operate on fundamental types, eg
std::string numberToString(double toConvert);
std::string numberToHexString(double toConvert);
int intToXSignificantPlaces(const int& number,
unsigned char numberOfSignificantPlaces);
bool numbersAreApproximatelyEqual(float tollerance);
//etc....
Syntactically it would be nicer (and more oop) to do the following:
intWrapper.toString();
intWrapper.toHexString();
//etc
Also it would allow me to implement bigint classes (int128, etc) and have those and the smaller ones (based on fundamental types) use identical interfaces.
Finally each wrapper could have a static instance of itself called max and min, so the nice syntax of int32::max and int32::min would be possible.
However, I have a few concerns that I would like to address before doing this (since it is mostly syntactical sugar and these types would be used so commonly any extra overhead could have a significant performance impact).
1) Is there any additional function calling overhead when using someClass.operator+(), someClass.operator-() etc over just int a + int b? If so, would inlining operator+() eliminate ALL this overhead?
2) All external functions require the primitive type, eg glVertex3f(float, float, float) could not simply be passed 3 floatWrapper objects, is there a way to automatically make the compiler cast the floatWrapper to a float? If so, are there performance impacts?
3) Is there any additional memory overhead? I understand(?) that classes with inheritance have some sort of virtual table pointer and so use slightly more memory (or is that just for virtual functions?), but assuming these wrapper classes are not inherited from/are not child classes there isn't any additional memory use using classes instead of fundamental types, is there?
4) Are there any other problems / performance impacts this could cause?