Advertisement

Overload primitive types in c++

Started by April 18, 2001 01:42 PM
1 comment, last by zel 23 years, 9 months ago
Is it possible to overload or create new classes for all basic primitives (int, bool, float) without any serious performance losts ? If you inline all operations. It really doesn''t make sense for anything but float comparsions (at least I have special functions that counts for precision losts). But it would be interesting to hear what you have to say anyway. I mean, even if you don''t loose anything because the functions are declared as inline, the optimizer might not be able to optimize as much as normally if the primtives are objects instead of just primitives. But one use would be to have one class for debugging and one for release. That way you could discover error at the same time as you don''t loose any performance when you compile the program with the release class. I guess you could just typedef the primitives at release time.
One way to do it would be to derive a new class from a base class and modify that. That way you have all the performance of the built in version, plus you can add new functionality to it.
Advertisement
Anthrax: that would be an improper use of polymorphism. Many people don''t realize that there is a cost to polymorphism: 1 extra indirection per call to virtual function + 1 pointer to static vtable + static memory for vtable. Polymorphism has its uses, the most important being an elegant way to remove your code of "switch (type) { ... }" statements. But that doesn''t apply at all here.

Zel: you cannot overload the primitives. You can create a class that acts like the primitive, and yes, it would make sense in many cases to do so, like infinite-precision integers or a stand-in for floats/doubles that handles floating point ops differently. If you inline all the member functions and are careful to make your class have the same behaviors as its built-in equivalent, it can be extremely useful and efficient. While I know you cannot make a user type that has the exact same properties of and is more efficient than a built-in type (that would just be silly), it''s possible to create types that are extremely efficient when built-in types will not do the job you need to or the way you need it done.

I highly recommend Scott Meyer''s books (Efficient C++ and More Efficient C++) for creating user types that follow all the rules of built-in types.

This topic is closed to new replies.

Advertisement