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
}
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.
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.
" 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With