deducing references to const from rvalue arguments

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?

Answers


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).


Need Your Help

When I update my Avatar picture, it changes all users picture

ruby-on-rails ruby avatar

I seem to be making an error in my code. I've been looking at two of my past projects and in one I have a pictures table to associate a picture_id with a user but on a different project it wasn't e...

Segfault on very simple source

c segmentation-fault freetype

I'm trying to write a simple script using the FreeType library. The segfault is occurring during execution of the FT_Set_Pixel_Sizes method, though I'm using it correctly. Any help would be great. ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.