I have a template base class like this:
template<typename T, std::size_t Size>
class VectorT
{
public:
typedef T data_type;
}
and a few specialised derived classes:
template<typename T>
class Vector2d : public VectorT<T, 2U>
{ // some specialised functions }
template<typename T>
class Vector3d : public VectorT<T, 3U>
{ // some other specialised functions }
and these work fine. Howerver, I have a few free-standing functions for operators. For example:
template<typename T, size_t Size>
VectorT<T, Size> operator*(T lhs, const VectorT<T, Size>& rhs)
{
...
}
Unfortunately these do not work for my derived classes, because they return a VectorT<T, Size> instead of a Vector2d<T>.
So I tried with
template<V>
V operator*(typename V::data_type lhs, const V& rhs)
{
...
}
and this works fine, however it can lead to ambiguities because it sucks in anything else with a data_type member.
How can I get around this: how can I write type safe functions that only work with my vector base, or any derivatives of?
I am trying to get around having to re-declare and redefine the operators again for the subclasses.
You could add yet another base class, one that is independent of the template parameters, and use SFINAE to disable calls for types other than derived from such base:
Note that
is_base_of< X, X >is alwaystrue, so this function will work for one more type than required, namely the base classVectorBase.If you are using a compiler that implements TR1, you can replace
boost::forstd::in both places where is used.