推导 LValue 引用类型
Deducing LValue Reference type
有很多关于模板参数推导的讨论和澄清,特别是引用折叠和"universal references."这个问题通过相关细节:How does auto deduce type?, and this paper by Scott Meyers goes into even more detail and perhaps gives more examples and wider context: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers, and his cppcon slides: http://www.aristeia.com/TalkNotes/C++TypeDeductionandWhyYouCareCppCon2014.pdf。
我的问题涉及以下代码:
template <typename T> void f(T t) { t = 0; }
int main() {
int i{5};
int &ir{i};
f(ir);
cout << i << endl; // 5
f<decltype(ir)>(ir);
cout << i << endl; // 0
}
为什么我的模板函数 f
不能推断出它们键入 int &
?根据 Scott Meyers 的幻灯片(幻灯片 7),ir
是左值引用这一事实被简单地 忽略了 。这完美地解释了这种行为,但为了完美地解释 that 我花了一些时间阅读参考和标准,试图找到它说的是什么:
If A is a reference type, the referred type is used by deduction.
这是旧的离线版本的参考资料(我通常使用的),尽管它是在 header 转换函数模板 下说的,并且我没有在标准中找到这个措辞。我发现的关闭我认为来自重载模板的部分排序规则,但我不相信它会在这里应用,即使它是我正在寻找的。
标准中是否有指定此行为的某处,或者它是否被我忽略的其他行为所暗示?我真的很想告诉别人 "that doesn't deduce type int &
because of these words in the standard right here."
C++中没有引用类型的表达式。 变量ir
的类型是int&
,但是表达式ir
的类型是int
。后一种类型用于类型推导,因为函数参数总是 expressions(除了 braced-init-lists 的特殊情况)。
If an expression initially has the type “reference to T
” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T
prior to any further analysis.
The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.
有很多关于模板参数推导的讨论和澄清,特别是引用折叠和"universal references."这个问题通过相关细节:How does auto deduce type?, and this paper by Scott Meyers goes into even more detail and perhaps gives more examples and wider context: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers, and his cppcon slides: http://www.aristeia.com/TalkNotes/C++TypeDeductionandWhyYouCareCppCon2014.pdf。
我的问题涉及以下代码:
template <typename T> void f(T t) { t = 0; }
int main() {
int i{5};
int &ir{i};
f(ir);
cout << i << endl; // 5
f<decltype(ir)>(ir);
cout << i << endl; // 0
}
为什么我的模板函数 f
不能推断出它们键入 int &
?根据 Scott Meyers 的幻灯片(幻灯片 7),ir
是左值引用这一事实被简单地 忽略了 。这完美地解释了这种行为,但为了完美地解释 that 我花了一些时间阅读参考和标准,试图找到它说的是什么:
If A is a reference type, the referred type is used by deduction.
这是旧的离线版本的参考资料(我通常使用的),尽管它是在 header 转换函数模板 下说的,并且我没有在标准中找到这个措辞。我发现的关闭我认为来自重载模板的部分排序规则,但我不相信它会在这里应用,即使它是我正在寻找的。
标准中是否有指定此行为的某处,或者它是否被我忽略的其他行为所暗示?我真的很想告诉别人 "that doesn't deduce type
int &
because of these words in the standard right here."
C++中没有引用类型的表达式。 变量ir
的类型是int&
,但是表达式ir
的类型是int
。后一种类型用于类型推导,因为函数参数总是 expressions(除了 braced-init-lists 的特殊情况)。
If an expression initially has the type “reference to
T
” ([dcl.ref], [dcl.init.ref]), the type is adjusted toT
prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.