Re: Adding members to a template class specialization?
Daniel Pitts wrote:
I have a Vector template class (math vector), where the number of
dimensions is one of the template parameters.
template<typename component_t, int dimensions>
class Vector {...}
I'd like to specialize for Vector<*,3> to add
template<typename component_t>
Vector<component_t, 3> Vector<component_t, 3>::crossProduct(const
Vector<component_t, 3> &other) const {...}
Since cross product only makes sense with vectors that have dimension=3.
Is this possible? Basically, I want a compile time error if you call
crossProduct on a vector that isn't 3d.
Yes, it's possible. You basically need to repeat all other stuff,
unfortunately.
Hmm, I think I figured out I can do it as a friend/external function,
but I'd like to try to do it as a member function. Is that possible?
Again, yes, it is. You will face the fact that the rest of the class
would have to be essentially repeated.
template<typename component_t>
Vector<component_t, 3> crossProduct(const Vector<component_t, 3> &a,
const Vector<component_t, 3> &b) {...}
Since you want to avoid repeating not only the declarations but also the
implementations of the class, you are better off extracting the common
part between those two Vector classes into a separate base class,
something like
template<class C, unsigned dim> class VectorBase {
... common stuff goes here ...
Vector& operator +=(Vector const&) {
return *this;
}
};
and then derive the generic vector and the specialisation (for dim==3)
from that base:
template<class C, unsigned dim> class Vector
: public VectorBase<C, dim> {
// nothing here
};
template<class C> class Vector<C,3>
: public VectorBase<C,3> {
Vector crossProduct(Vector const&) const;
};
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask