Boost logo

Boost :

From: Jeremiah Willcock (jewillco_at_[hidden])
Date: 2005-07-21 16:39:00


On Thu, 21 Jul 2005, Neal Becker wrote:

> I have a question on usage of enable_if for faking partial specialization of
> function templates.
>
> Suppose I have a func F that has a general implementation, and a partial
> specialization for std::complex<T>.
>
> The obvious way to do this is to forward to a class member:
>
> template<typename T>
> struct F_impl { void DoF (); };
>
> template<typename T>
> struct F_impl<std::complex<T> >{ void DoF (); };
>
> template<typename T>
> void F () { F_impl<T>(); }
>
> Alternatively, I can define is_cmplx:
> template<typename T>
> struct is_cmplx {
> static const bool value = false;
> };
>
> template<typename FLT>
> struct is_cmplx<std::complex<FLT> > {
> static const bool value = true;
> };
>
> And use enable_if/disable_if.
>
> Both work. My question is, why would I prefer one over the other approach?

For the example you give, I don't think there is much difference between
the approaches. The first example, however, is more extensible; you (or
users of your library) can add new partial specializations of the struct
without needing to modify the existing source code. With the second
version of the code, you are stuck with those two cases for the function
because the overloads of F() you write are of equivalent priority for
partial ordering, although a user can specialize is_cmplx to change its
definition for particular types. A user can also add a third overload,
but it must be more specific by partial ordering than the two you give,
and so they cannot write an overload that uses enable_if as its only
argument type restriction. An advantage of the second approach is that
you can easily add more overloads of F(), including overloads which do not
return void or which cannot be expressed by a forwarding function (such as
taking a parameter by copy for one overload and by non-const reference for
another). The second approach also allows more complicated conditions
than just matching of particular type patterns to be used directly,
although enable_if on partial specializations of structures allows that
for the first example as well. Does this answer your question?

                                                        Jeremiah Willcock


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk