你确实有多种选择,特别是如果你愿意改变签名。
最有可能的,要发出错误信号,以及异常是非常有趣的位置:
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);
}
或者更改签名,您可以包括无效的概念:
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;
}
哪可以使用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;
}
,或在不改变签名,你可能希望使用空对象,但这几乎不是最好的选择(它将你限制为嵌入无效概念的对象,并且这样的对象更好地被重构为不具有无效概念,而是依赖于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.
}
它应该抛出异常 - 相关[问题](http://stackoverflow.com/q/13416488/952747)。 – deepmax
你应该抛出。 – 0x499602D2
我该怎么做? – user2175394