Limit template function to base and derived types?

I have a template base class:

template<typename T, std::size_t Size>
class VectorT
{
public:
    typedef T data_type;
}

and several specialized 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 they work fine. Howerver, I have several independent functions for operators. For instance:

template<typename T, size_t Size>
VectorT<T, Size> operator*(T lhs, const VectorT<T, Size>& rhs)
{
    ... 
}

Unfortunately, this does not work for my derived classes because they return VectorT<T, Size>instead Vector2d<T>.

So, I tried using

template<V>
V operator*(typename V::data_type lhs, const V& rhs)
{
    ... 
}

and this works great, however, it can lead to ambiguity because it sucks anything else with the data_type element.

How can I get around this: how can I write safe type functions that work only with my vector base or with any derivatives?

I'm trying to get around to re-declaring and overriding statements again for subclasses.

+5
2

, , SFINAE, :

struct VectorBase {};

template< typename T, std::size_t Size >
class VectorT : public VectorBase { ... }

template< typename V >
typename boost::enable_if< boost::is_base_of< VectorBase, V >, V >::type
operator*( V lhs, V const& rhs ){ ... }

, is_base_of< X, X > true, , , VectorBase.

, TR1, boost:: std:: , .

+7

, "" . :

  • ( , , )
  • VectorT<>& VectorT . , VectorT . .
  • , K-ballo.
+1

All Articles