A current project using multiple libraries has at least two definitions of essentially the same struct
struct CvPoint {
int x, y;
};
struct Vector2i {
int x, y;
};
Often we have a variable of one type but need to pass it to a function that takes the other type so the compiler barks "cannot convert parameter..."
What's the best way to deal with this? pointer casting, overloaded cast??
If its within your power, your best bet would be to standardize on a single class but I am guessing this is beyond your control.
The answer to your question though is depends. Real helpful answer eh? ;)
If there is every any possibility the object you are dealing with isn't going to be of the type you expect it to be, you should use dynamic_cast. Otherwise a standard cast or static_cast will do the trick. Unlike a dynamic_cast a static_cast performs no runtime checks so it will perform a bit faster. Then again, a dynamic_cast will return null if the object being casted isn't actually what you say it is, while a static_cast will simply blow up in spectacular fashion, so be sure you are dealing with the object type you expect. A standard cast is like a static_cast with even less restrictions.
Oh, one last gotcha, dynamic_cast depends on RTTI being enabled, which this days will generally not be an issue, but it is one of those things to be aware of.
Both are unsafe. The only safe way to do it would be to convert by copying to a new object (either implictily or explicitly).
1 2 3 4 5 6 7 8 9
// pick a better name than NameMe:
CvPoint NameMe(const Vector2i& v) { return CvPoint(v.x,v.y); }
Vector2i NameMe(const CvPoint& v) { return Vector2i (v.x,v.y); }
Vector2i example;
// pass 'example' to a function that takes a CvPoint:
SomeFunction( NameMe(example) );