为什么以下程序没有选择与第一个模板参数相同类型的参数? [英] Why does the following program not select the argument of the same type as the first template parameter?
问题描述
我正在尝试编写一个函数,使 f< T(args ..)
返回类型为 T $的第一个参数c $ c>。
I am trying to write a function such that f<T>(args..)
returns the first parameter of type T
.
下面的程序似乎总是选择第一个专业化,因此打印 97
(ASCII代码'a'
)。尽管第二个不需要将 char
转换为 int
。
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?
我是SFINAE和元编程的新手。
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);
}
推荐答案
您的代码的第一个函数参数是在非推论上下文中。 enable_if< expr,T> :: type
不能推断出 T
。
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".
无法推断 T
, foo< int>(7)
不能使用该重载;编译器不知道 T
是什么。 foo< int,int>(7)
会调用它。
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)
现在 T
在推论中。我们不是要推论 R
(也不能从返回类型推论)。
now T
is in a deduced context. We aren't trying to deduce R
(nor can we deduce from a return type).
这篇关于为什么以下程序没有选择与第一个模板参数相同类型的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!