c++ - SFINAE with C++14 return type deduction -
c++ - SFINAE with C++14 return type deduction -
thanks c++14, we'll able curtail verbose trailing homecoming types; such generic min
illustration david abrahams 2011 post:
template <typename t, typename u> auto min(t x, u y) -> typename std::remove_reference< decltype(x < y ? x : y) >::type { homecoming x < y ? x : y; }
under c++14 homecoming type can omitted, , min
can written as:
template <typename t, typename u> auto min(t x, u y) { homecoming x < y ? x : y; }
this simple example, homecoming type deduction useful generic code, , can avoid much replication. question is, functions such this, how integrate sfinae techniques? example, how can utilize std::enable_if
restrict our min
function homecoming types integral?
you can't sfinae function using homecoming type if you're using homecoming type deduction. mentioned in proposal
since homecoming type deduced instantiating template, if instantiation ill-formed, causes error rather substitution failure.
you can, however, utilize extra, unused template parameter perform sfinae.
template <class t, class u> auto min1(t x, u y) { homecoming x < y ? x : y; } template <class t, class u, class..., class = std::enable_if_t<std::is_integral<t>::value && std::is_integral<u>::value>> auto min2(t x, u y) { homecoming x < y ? x : y; } struct foo {}; min1(foo{}, foo{}); // error - invalid operands < min1(10, 20); min2(foo{}, foo{}); // error - no matching function min2 min2(10, 20);
live demo
c++ templates sfinae c++14
Comments
Post a Comment