Abh*_*mar 6 c++ templates sfinae variadic-templates c++14
I am trying to write a function such that f<T>(args..) returns the first parameter of type T.
The following program seems to always select the first specialization thus printing 97 (ASCII code of 'a'). Though the second one wouldn't require converting char to int. Could someone please explain the behavior?
I am new to SFINAE and meta-programming.
#include <iostream>
using namespace std;
template <typename T, typename ...Ts>
T f(T a, Ts... args) {
return a;
}
template <typename R, typename T, typename ...Ts>
R f(typename enable_if<!is_same<R, T>::value, T>::type a, Ts... args) {
return f<R>(args...);
}
int main() {
cout << f<int>('a', 12);
}
Run Code Online (Sandbox Code Playgroud)
的第二个模板参数std::enable_if应该是R,这是您希望拥有的。
以下应该工作
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
}
Run Code Online (Sandbox Code Playgroud)
您的代码的第一个函数参数位于非推导上下文中。 enable_if< expr, T >::type 无法推断T。它处于“非演绎上下文”中。
无法推断T,foo<int>( 7 )无法使用该重载;编译器不知道是什么T。 foo<int,int>(7)会调用它。
template <typename R, typename T, typename ...Ts>
typename enable_if<!is_same<R, T>::value, R>::type f(T a, Ts... args)
Run Code Online (Sandbox Code Playgroud)
现在T是在推论的背景下。我们并不是试图推断R(也不能从返回类型推断)。