It seems like SO often I need to attach a "valid" flag to a standard type. For example - I have a function called "CalculateLunchTime" that I pass a vector of times. If the vector has 0 elements, they did not take a lunch, so the duration is 0 minutes. If the vector has 2 elements, subtract them and that is the lunch duration. If the vector has one element, it doesn't make sense to calculate a duration, but I don't want to return 0 because that was for the first case. In this case the valid range is >0, so of course I could return -1 or something, but it really bothers me having these magic numbers running around. I would really want to do something like

ValidDouble LunchTime(vector<time> &Times)
{
ValidDouble lunchtime;
if(Times.size() == 1)
lunchtime.valid = false;
else
{
lunchtime = Times(1) - Times(0);
lunchtime.valid = true;
}

return lunchtime;

}

Of course I could make a struct with a double and a bool, but I have really never seen anyone else do that so I feel like it could be a bad idea (why?). It would seem a little nicer if I could derive ValidDouble from double. Is that possible?

Thanks,
Dave

You want a struct with a double and a bool.

You should never use inheritance except as a mechanism for polymorphism -- one reason being that 'putting stuff into structs' or classes (a.k.a. composition) is sufficient, another being that using inheritance leads to a complete clusterfuck of disorganization, when you're using it for things that composition is good for. Basically when you have a type T inheriting from U, you should ask, "is T a U"? Well, is [something that is either a double or invalid] a double? No, because invalids aren't really doubles.

It might be helpful to see how other languages handle this problem.

C# has a type Nullable<double> that lets you create values that are either a double or invalid -- and it has special syntax for it, too:

double? x = 3.0;
double? y = null; // i.e. invalid

That's equivalent to using a pointer to a double, where the pointer could be null.

The reason I don't recommend using that kind of solution for C++ is because C++ doesn't have automatic garbage collection, and allocating stuff is a bit more expensive than in garbage collected languages.

A lot of times in C# or Java, people just represent 'invalid' values with null references. In languages without null references, they create a polymorphic type that is either 'just a value of type t' or 'nothing'.

And in C++ you can't inherit from double anyway. So a struct containing a double and the bool is good.

As an exercise you might want to create a class Maybe<T> that either contains a value of type T or is invalid.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.