RFR: 8251274: Provide utility types for function SFINAE using extra template parameters

Kim Barrett kim.barrett at oracle.com
Fri Aug 7 08:33:06 UTC 2020


Please review this change which adds some utility alias templates for
function template SFINAE via additional non-type template parameters with
default values.  These aliases can also be used for class template SFINAE
with a small change to current usage.

With C++98/03 there are two ways to use enable_if with function templates:

(1) As the return type
(2) As an extra parameter

Both are syntactically messy, polluting the function signature.

C++11 adds a third way, using an extra anonymous non-type template parameter
with a default value, i.e.

  // This overload is only considered when T is an integral type.
  template<typename T, std::enable_if_t<std::is_integral<T>::value, int> = 0>
  void foo(T x) { ... }

There's still a lot of syntactic noise in that, but we can substantially
reduce the noise using alias templates.  With the proposed utilities, that
can be written as

  // This overload is only considered when T is an integral type.
  template<typename T, EnableIfT<std::is_integral<T>> = 0>
  void foo(T x) { ... }

The trailing " = 0" is a small remaining syntactic annoyance.  That can't be
eliminated without the use of macros though.  While I like macros, this
didn't seem to me to rise to the level of being worth using them.

There are four new aliases:

template<bool V> EnableIfX;          // int if V, else error.
template<typename T> EnableIfT;      // int if T::value, else error.
template<typename... T> EnableIfAnd; // int if Conjunction<T...>::value, else error.
template<typename... T> EnableIfOr;  // int if Disjunction<T...>::value, else error.

I'm open to bikeshedding on the names of EnableIfX and EnableIfT.

(I'm disappointed that there's even a need for the distinction between
EnableIfX and EnableIfT.  A macro can completely hide that distinction
(along with the conventional " = 0" default value if desired).
Unfortunately, the implementation of such a macro foundered on MSVC bugs
that I was unable to work around.  To be fair, my preferred implementation
also ICE'd gcc.)

CR:
https://bugs.openjdk.java.net/browse/JDK-8251274

Webrev:
https://cr.openjdk.java.net/~kbarrett/8251274/open.00/

Testing:
tier1, along with conversion of some existing code to use the new mechanism.



More information about the hotspot-dev mailing list