I have a question, though it is not limited to C++. How to return totally different class from one function?
f() {
in case one: return A;
in case two: return B;
in case three: return C;
}
For example, I have two balls in the space, according to the position and the size, there are three situations for the two balls to intersect with each other, i.e, non-intersection, at point, a and circle. How can I return different class in one function?
Thanks.
If you can afford Boost then this sounds like a perfect application for Boost.Variant.
You then process your result with a static visitor:
EDIT: The visitor class must derive from
boost::static_visitorUPDATE: Prompted by some critical comments I’ve written a little benchmark program. Four approaches are compared:
boost::variantboost::anyThese are the results in my home computer, when I compile in release mode with default optimizations (VC08):
Using
boost::variantis faster than a union and leads (IMO) to the most elegant code. I’d guess that the extremely poor performance of the class hierarchy approach is due to the need to use dynamic memory allocations and dynamic dispatch.boost::anyis neither fast nor especially elegant so I wouldn’t consider it for this task (it has other applications though)