C++ 模板推导
C++模板推导
code
int a = 10;
int &b = a;
template<typename T>
void func(T t)
{
}
template<typename T>
void bar(T& t)
{
}
int main()
{
func(b);// using T = int;
// 而不是 using T = int&;
bar(b); // using T = int;
// 而不是 using T = int&;
}
解释
- 在表达式中,引用的标识符表达式会被调整为引用的类型expr.type.1。
If an expression initially has the type “reference to T”, the type is adjusted to T prior to any further analysis; the value category of the expression is not altered. Let X be the object or function denoted by the reference.
- 函数模板推导时,函数模板的函数形参(带有模板形参)如果是引用,则会使用引用的类型来推导(表现为剔除
&符)temp.deduct.call.3
If P is a reference type, the type referred to by P is used for type deduction.
分析
int main()
{
func(b);
// 这里 type(b) == int&,调整为int
bar(b);
// 这里 T&会被调整为T,b同上。
}
浙公网安备 33010602011771号