Reputation: 13313
The trivial solution would be:
class Number
{
public:
bool isFinite();
bool isPositive();
double value();
...
private:
double value_;
bool isFinite_;
bool isPositive_;
...
};
The thing that worries me is efficiency:
From Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers:
Even when small objects have inexpensive copy constructors, there can be performance issues. Some compilers treat built-in and user-defined types differently, even if they have the same underlying representation. For example, some compilers refuse to put objects consisting of only a double into a register, even though they happily place naked doubles there on a regular basis. When that kind of thing happens, you can be better off passing such objects by reference, because compilers will certainly put pointers (the implementation of references) into registers.
Is there a way to bypass the efficiency problem? For example a library that uses some assembly language magic?
Upvotes: 2
Views: 310
Reputation: 882136
For your specific example, I would just use doubles as they are rather than in a class. They're well adapted and defined for handling infinities.
In a more general sense, you should use the trivial solution and only worry about performance when (or, more likely, if) it becomes a problem.
That means code it up and test it in many of the scenarios you're going to use it for.
If it still performs within the bounds of your performance requirements, don't worry about trying to optimise it. And you should have some performance requirements slightly more specific that "I want it to run a s fast as possible" :-)
Remember that efficiency doesn't always mean "as fast as possible, no matter the cost". It means achieving your goals without necessarily sacrificing other things (like readability or maintainability).
If you take an complete operation that makes the user wait 0.1 seconds and optimise it to the point where it's ten times faster, the user won't notice that at all (I say "complete" because obviously, the user would notice a difference if it was done ten thousand times without some sort of interim result).
And remember, measure, don't guess!
Upvotes: 2
Reputation: 14708
There is very little reason to implement a Number class for a double. The double format already implement Infinity, NaN, and signage as part of the raw basic double type.
Second, you should write your code first aiming for correctness, and then try to optimize later, at which time you can look at factor out specific data structure and rewrite code and algos.
Modern day compilers are typically very efficient in writing good code, and typically does a way better job than most human programmers does.
Upvotes: 6