SFINAE with C++14 return type deduction

一曲冷凌霜 提交于 2019-11-28 11:21:49

You can't SFINAE the function using the return type if you're using return type deduction. This is mentioned in the proposal

Since the return type is deduced by instantiating the template, if the instantiation is ill-formed, this causes an error rather than a substitution failure.

You can, however, use an extra, unused template parameter to perform SFINAE.

template <class T, class U>
auto min1(T x, U y)
{ return 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)
{
    return x < y ? x : y; 
}

struct foo {};

min1(foo{}, foo{}); // error - invalid operands to <
min1(10, 20);

min2(foo{}, foo{}); // error - no matching function min2
min2(10, 20);

Live demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!