Re: Template specialization or overloading?
On Aug 19, 3:33 pm, "saneman" <as...@asd.com> wrote:
I have template function that should do the same for two classes A and B:
[...]
You could do some compile-time dispatching via "tag classes" and some
meta programming magic. This is often done in the STL (for example
iterator traits):
struct is_A_or_B_tag {};
struct is_not_AB_tag {};
template<typename T> struct param_a_traits { typedef is_not_AB_tag
category; };
template<> struct param_a_traits<A> { typedef is_A_or_B_tag
category; }
template<> struct param_a_traits<B> { typedef is_not_AB_tag
category; }
template<typename T, typename U, typename X>
void f_with_tag(T t, U u, X ab, is_A_or_B_tag) {
// 'ab' is of type A or B
}
template<typename T, typename U, typename X>
void f_with_tag(T t, U u, X x, is_not_AB_tag) {
// 'x' is NOT of type A nor B
}
template<typename T, typename U, typename X>
inline void f(const T & t, const U & u, const X & x) {
f_with_tag(t, u, x, typename param_a_traits<X>::category());
}
This is a trick to emulate concept-based overloading. Also, you may
want to replace some "T t"-declarations to "const T& t" when possible.
Otherwise you'll be copying the objects.
Cheers,
SG