
On Tue, Oct 5, 2010 at 9:20 PM, Matt Calabrese <rivorus@gmail.com> wrote:
I've been noticing that a lot of times in 0x code I've found it useful to create a very simple "auto function" macro that uses trailing return type syntax with decltype with 1-liner functions that automatically repeats the same expression in both the return type and the return statement.
#define AUTO_FUN( name, param_list, expression ) \ auto name param_list -> decltype( expression ) { return expression; }
Why not simply auto name = [&](param_list){ return expression; } ?
There are two big advantages to this. The first and most obvious one is that it reduces redundancy when you have a 1-line function template which has a difficult to deduce return type that you generally would use decltype on, and the more subtle benefit is that since the exact expression is repeated in the return type you automatically get "perfect-fit" SFINAE. By that I mean it provides a quick way to SFINAE-out potential instantiations before instantiating the implementation. Because of this, even though a return type may be simple to deduce without decltype, the macro is still a valuable tool since it can cause substitution to fail if the body of a function template would fail to instantiate. You get very basic, automatic, syntax-only concept checking for free. It's a simple macro, but I find that it gets lots of use.
I don't know if my suggestion would give sfinae, though. Yechezkel Mett