Kol*_*nya 6 c++ return exception function return-value
假设我们想要创建一个计算两条线交点的函数.交点不总是定义的或唯一的.如何在函数的签名中反映出来?
我想出了这些选择:
bool getIntersectionPoint ( Line& a, Line& b , Point& result );
如果行是并行的,则返回false.否则返回true并将结果写入变量.
Point getIntersectionPoint ( Line& a, Line& b );
如果线条平行,则抛出异常.
[update]
如果我们创建2个函数bool doLinesIntersect(const Line&, const Line&);,Point twoLinesIntersection(const Line&, const Line&);第二个函数仍然可以在第一个函数返回false后调用.
恕我直言,线相交产生对象,这就是为什么诚实地说
boost::variant<Empty, Point, Line> intersect(Line const & l1, Line const & l2)
和辅助函数,例如
boost::optional<Point> getIntersectionPoint(Line const & l1, Line const & l2)
bool isParallel(Line const & l1, Line const & l2)
编辑: 如果您不想使用 boost 库,您可以轻松创建简单的类似物:
struct intersection_result_t
{
enum isec_t
{
isec_empty, isec_point, isec_line
}
intersection_result_t()
: type_(isec_empty)
{
new (storage_) Empty();
}
intersection_result_t(Empty const & e)
: type_(isec_empty)
{
new (storage_) Empty(e);
}
intersection_result_t(Point const & p)
: type_(isec_point)
{
new (storage_) Point(p);
}
...
intersection_result_t(intersection_result_t & ir)
: type_(ir.type_)
{
switch(ir.type_)
{
case isec_empty:
new (storage_) Empty(*static_cast<Empty*>(ir.storage_));
case ....
}
}
private:
void destroy()
{
switch(type_)
{
case isec_empty:
operator delete (static_cast<Empty*>(storage_), storage_);
case ....
}
}
private:
char storage_[MAX(sizeof(Empty), sizeof(Point), sizeof(Line))];
isec_t type_;
};
Run Code Online (Sandbox Code Playgroud)
等等,需要更多的开关。或者您可以使用模板。对于可选的,仅使用initialized_而不是type_跟踪构造状态。