Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template reference argument deduction failure in C++

Why following code doesn't compile in C++14 compiler? If I use

const int i = 10;
int n = fun(i);

The compiler gives an error.

But, If I use

int n = fun(10);

instead of above statements, it's working fine.

Example:

template<typename T>
int fun(const T&&)
{
    cout<<"fun"<<endl;
}

int main()
{
 // int i = 10;         // Not work
    const int i = 10;   // Not work
    int n = fun(i);  
 // int n = fun(10);    // Working fine
}
like image 702
msc Avatar asked Aug 02 '17 12:08

msc


People also ask

What is template argument deduction?

Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.

What are template arguments?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What is Typename C++?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.


1 Answers

It fails because adding the const prevents it from being a forwarding reference. It becomes a regular reference to a const rvalue:

[temp.deduct.call/3]

... A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])). ...

And you pass it an lvalue. It fails the match.

like image 178
StoryTeller - Unslander Monica Avatar answered Nov 07 '22 15:11

StoryTeller - Unslander Monica