Partial custom function template with argument template
I have a template function (for simplicity, let it "add")
template<typename T>
inline T add(const T a, const T b)
{
return a+b;
}
I can specialize it for certain types, but what I would like to do is specialize in a template type.
In my case, my template type is called Vec2<T>. This is a two-dimensional trigonometric vector (both in x and y, not a C ++ vector!)
What I would like to do is specialize in my function addfor the general case Vec2<T>, and not specialize in each type with which it can be used Vec2.
The library from which it Vec2<T>comes has typedefs for V2d(double), V2f(float) and V2i(int).
I can specialize for each of them using something like:
template<>
inline V2f add<V2f>(const V2f a, const V2f b)
{
return V2f(a.x + b.x, a.y + b.y);
}
, , , - :
template<typename S>
inline Vec2<S> add<Vec2<S> >(const Vec2<S> a, const Vec2<S> b)
{
return Vec2<S>(a.x + b.x, a.y + b.y);
}
, , .
. , , , :
template<typename> struct add_impl;
template<typename T>
T add(const T a, const T b)
{
return add_impl<T>::do_it(a, b);
}
template<typename T>
struct add_impl {
static T do_it(const T a, const T b) { return a + b; }
};
template<typename S>
struct add_impl<Vec2<S> > {
static Vec2<S> do_it(const Vec2<S> a, const Vec2<S> b) {
return Vec2<S>(a.x + b.x, a.y + b.y);
}
};