从右值参数推导const的引用 [英] deducing references to const from rvalue arguments
问题描述
好吧,这可能看起来像一个愚蠢的问题,但在这里它是:
template< typename T&
void foo(T& x)
{
}
int main()
{
foo(42)
//在'void foo(T&)[with T = int]'
}
传递参数1时出错
什么是阻止C ++用 T = const int
foo >
问题是模板类型扣除必须计算出完全匹配,在这种情况下,因为的参考在签名中,精确匹配需要一个左值。值42不是一个左值,而是一个右值,用 const int
解析 T
完美搭配。由于模板类型推演限于完全匹配,因此不允许扣除。
如果不使用文字使用不可变的左值,则编译器将推导出类型适当,因为 const int
将成为参数的完美匹配:
const int k = 10;
foo(k); // foo< const int>(const int&)是一个完美的匹配
特殊规则,它允许调用一个带有右值的const引用(不可变的左值)的函数,这意味着创建一个临时左值,该值稍后绑定到引用,但是对于该规则,在函数中必须具有该签名这就是为什么明确地说明模板的类型是 const int
works: foo< const int>(42)
。
Okay, this may seem like a silly question, but here it goes:
template <typename T>
void foo(T& x)
{
}
int main()
{
foo(42);
// error in passing argument 1 of 'void foo(T&) [with T = int]'
}
What is preventing C++ to instantiate the foo
function template with T = const int
instead?
The problem is that template type deduction has to work out an exact match, and in that particular case, because of the reference in the signature, an exact match requires an lvalue. The value 42, is not an lvalue, but rather an rvalue, and resolving T
with const int
would not yield a perfect match. Since template type deduction is limited to exact matches, that deduction is not allowed.
If instead of using a literal you use a non mutable lvalue, then the compiler will deduce the type appropriatedly, as const int
will become a perfect match for the argument:
const int k = 10;
foo( k ); // foo<const int>( const int & ) is a perfect match
Now there is a special rule that enables calling a function that takes a const reference (nonmutable lvalue) with an rvalue, that implies creation of a temporary lvalue which is later bound to the reference, but for that rule to kick in the function has to have that signature before hand, which is why explicitly stating that the type of the template is const int
works: foo<const int>(42)
.
这篇关于从右值参数推导const的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!