Why does the following program not select the argument of the same type as the first template parameter?
The second template argument of the std::enable_if
should be the R
, which is what you desire to have.
Following should work
template < typename R, typename T, typename ...Ts>
typename enable_if<!is_same<R, T>::value, R>::type f(T const& t, Ts&&... args)
// ^^^ ^^^^^^^^^^^
{
return f<R>(std::forward<Ts>(args)...); // forward the args further
}
Your code's first function parameter is in a non-deduced context. enable_if< expr, T >::type
cannot deduce T
. It is in a "non-deduced context".
Being unable to deduce T
, foo<int>( 7 )
cannot use that overload; the compiler does not know what T
is. foo<int,int>(7)
would call it.
template <typename R, typename T, typename ...Ts>
typename enable_if<!is_same<R, T>::value, R>::type f(T a, Ts... args)
now T
is in a deduced context. We aren't trying to deduce R
(nor can we deduce from a return type).