English 中文(简体)
从右值参数推导对const的引用
原标题:deducing references to const from rvalue arguments

好吧,这个问题可能看起来很傻,但它是这样的:

template <typename T>
void foo(T& x)
{
}

int main()
{
    foo(42);
    // error in passing argument 1 of  void foo(T&) [with T = int] 
}

是什么阻止C++用T=const-int实例化foo函数模板?

最佳回答

问题是模板类型推导必须计算出精确匹配,在这种特殊情况下,由于签名中的引用,精确匹配需要一个左值。值42不是一个左值,而是一个右值,用const int解析T不会产生完全匹配。由于模板类型的推导仅限于精确匹配,因此不允许进行该推导。

如果不是使用文字,而是使用不可变的左值,那么编译器将适当地推导类型,因为const-int将成为参数的完美匹配:

const int k = 10;
foo( k );            // foo<const int>( const int & ) is a perfect match

现在有一个特殊的规则可以调用一个带有右值的const引用(非可变左值)的函数,这意味着要创建一个稍后绑定到引用的临时左值,但要使该规则生效,函数必须先有该签名,这就是为什么显式声明模板的类型为<code>const int</code>有效:<code>foo<;const int>;(42)。

问题回答

这是规则;-)。如果让编译器从参数中推导类型,它会选择最简单的方法。

在我看来,这并不是不合理的。你的模板说它需要一个非常量引用,所以它不使用右值编译。

你可以在调用站点告诉它你的意思:<code>foo<;int常量>;(42)或更改您的模板以明确它不需要可变引用:template<;typename T>;void foo(T const&;x){}

在C++11中,您可以有更多的选项来表达您的模板将接受和不接受的内容。

无论是模板函数还是普通函数,右值都不能通过引用传递。(因此const T&;有效,但T&;[/code>无效)。

是什么阻止C++用T=const int实例化foo函数模板

Suppose, C++ allows and makes T = const int instead. Now after sometime you change foo as,

template<typename T>
void foo (T& x)
{
  x = 0;
}

现在编译器必须生成错误。对于最终用户来说,这种体验会很奇怪,对于x=0这样的有效语句来说它开始出现错误。这可能就是为什么编译器在第一阶段阻止自己的原因!





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?