[英]Why does std::is_same give a different result for the two types?
In the code below, why do the two ways of invoking fun
: fun(num)
and fun<const int>(num)
, give a different result when compiling? 在下面的代码中,为什么在编译时调用
fun
的两种方法fun(num)
和fun<const int>(num)
给出不同的结果?
#include <iostream>
using namespace std;
template<typename T, typename = typename enable_if<!std::is_same<int, T>::value>::type>
void fun(T val)
{
cout << val << endl;
}
int main(void)
{
const int num = 42;
fun(num); //ERROR!
fun<const int>(num); //Right
return 0;
}
The parameter is declared as pass-by-value; 参数声明为传递值; then in template argument deduction , the top-level const qualifier of the argument is ignored.
然后在模板参数推导中 ,将忽略该参数的顶级const限定符。
Before deduction begins, the following adjustments to P and A are made:
在扣除开始之前,对P和A进行以下调整:
1) If P is not a reference type,
1)如果P不是参考类型,
a) ...
一种) ...
b) ...
b)...
c) otherwise, if A is a cv-qualified type, the top-level cv-qualifiers are ignored for deduction:
c)否则,如果A是cv限定类型,则将忽略顶级cv限定符以进行推导:
So given fun(num)
, the template parameter T
will be deduced as int
, not const int
. 因此,给定
fun(num)
,模板参数T
将推导为int
,而不是const int
。
If you change the parameter to pass-by-reference, the const
part will be preserved. 如果将参数更改为按引用传递,则将保留
const
部分。 eg 例如
template<typename T, typename = typename enable_if<!std::is_same<int, T>::value>::type>
void fun(T& val)
Then for fun(num)
, T
will be deduced as const int
. 然后为了
fun(num)
,将T
推导为const int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.