I would like to know what this get function should return when the parameters don't meet the if condition
template <class Object>
const Object& SparseMat<Object>::get(int c, int r) //const
{
if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
{
return mObjects[c][r];
}
//what should I return here?
}
You should throw an exception:
#include <stdexcept>
throw std::out_of_range("Indexes are out of range");
You actually have multiple choices, especially if you are willing to change the signature.
Most likely, you want to signal an error, and exceptions are pretty interesting here:
template <class Object>
const Object& SparseMat<Object>::get(int c, int r) const
{
if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
{
return mObjects[c][r];
}
throw UnknownCoordinates(c, r, cCapacity, rCapacity);
}
Or, changing the signature, you can include the concept of nullity:
template <class Object>
Object const* SparseMat<Object>::get(int c, int r) const
{
if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
{
return &mObjects[c][r];
}
return nullptr;
}
Which can be made more explicit using boost::optional:
template <class Object>
boost::optional<Object const&> SparseMat<Object>::get(int c, int r) const
{
if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
{
return mObjects[c][r];
}
return boost::none;
}
Or, without changing the signature, you might wish to use a null object however this is hardly ever the best choice (it restricts you to objects that embed a concept of nullity, and such objects are better refactored not to have a nullity concept and instead rely on boost::optional<Object>)
template <class Object>
const Object& SparseMat<Object>::get(int c, int r) const
{
if((c >= 0)&&(c <= cCapacity)&&(r >= 0)&&(r <= rCapacity))
{
return mObjects[c][r];
}
return null; // where null is "static Object const null;" for example.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With