Tuesday, 6 August 2013

Design a class that can be convertible to/from other libraries

Design a class that can be convertible to/from other libraries

I wrote a small self-contained library (depends only on the C++ standard
library) that has its own built-in 3D vector class:
namespace mylibrary {
struct Vector {
double x, y, z;
// and constructors
// like:
Vector(double x, double y, double z);
// and operators
};
}
It's supposed to interact with other code that produces/uses 3D vectors.
Now, assume some other library, which has:
namespace otherlibrary {
struct Vector3 {
// some different definition
// And is still able to construct from 3 values
Vector3(double x, double y, double z);
};
doSomething(const Vector3& point); // do something with the point
}
This other library could be the plugin API for a 3D modelling tool, or a
3D engine. It also has the concept for a 3D vector, but it's of course a
different type than my library's vector, even though the semantics are
identical. Think of Python's duck typing: the type doesn't matter as long
as it behaves in the expected way.
Question:
What mechanism could I use to make my library's Vector be used
conveniently as an argument for otherlibrary::doSomething()?
That is, being able to write this:
otherlibrary::doSomething( mylibrary::Vector(...) );
I can certainly build my Vector class to have a templated constructor that
accepts any type T with "x, y, z" members, or with operator[], so it can
consume almost anything that makes sense to interpret as a 3D vector.
Would it be possible to do it the other way around?

No comments:

Post a Comment