Boost logo

Boost :

Subject: [boost] New, powerful way to use enable_if in C++0x
From: Matt Calabrese (rivorus_at_[hidden])
Date: 2011-04-11 14:15:04


I'm not sure if there is much interest in this or if someone else discovered
this as well, but I realized today that enable_if can be used in a new way
in C++0x. Traditionally when working with enable_if with function templates
you invoke it either in the return type or in an additional function
parameter of the function. Each of these has advantages and disadvantages.

The parameter form has the downside of augmenting the parameter list. The
most notable problems with this approach are that it can't be used with
overloaded operators that require a fixed number of arguments, and it can't
be used after a variadic argument list.

The return type use of enable_if is often preferred since it does not
involve augmenting the parameter list, meaning that it can be used with most
overloaded operators, but you still can't use it for conversion operations
and you can't use it all with constructors as they have no explicit return
type.

However, in C++0x, there is a new way to use enable_if by altering neither
the function parameter list nor the specification of the return type. It can
be used with operators, constructors, variadic function templates, and even
overloaded conversion operations (the latter of which was previously
considered impossible). The way to do it is with C++0x default function
template parameters.

Rather than try to explain any further in English, the following code should
demonstrate the approach fairly clearly (tested in GCC 4.5.2):
http://codepaste.net/23yo8o

There is only one drawback that I can think of off of the top of my head --
you can't refer to the function parameters by name for the enable_if
condition, whereas in C++0x if you use the return type form of enable_if
along with the new trailing return type form of function declarations you
can. I have never personally wanted to do this and I highly doubt that it's
common so this is likely entirely a non-issue, plus you can always use
std::declval anyway so you aren't actually losing any high-level
functionality. Are there any thoughts on this or drawbacks other than what I
mentioned? Should such use be added to the docs as supported behavior in 0x
compilers?

-- 
-Matt Calabrese

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