Consider the following C++ code
template <class... Args>
void f (const int x, const int y, Args&&... args) {
// Do something
}
As far as I understand,Args
here could either be lvalue or rvalue references, depending on the type deduction at compile time.
So, I should be able to call the function using -
float x = 40.0;
f<int, float, double>(10, 20, 30, x, 50.0);
This gives me an error saying that it could not cast x from type float
to type float&&
.
How do I define a function with a variadic template that accepts both lvalue and rvalue references.
You're half right.
Args&&
would be either an lvalue or rvalue reference. ButArgs
itself is either an lvalue reference or not a reference. A simpler case:When you specify
float
forx
, you are specifying that that particular argument will have typefloat&&
, and you cannot implicitly convert an lvaluefloat
to an rvalue. You would have to cast it (viastd::move
):Or specify that it's an lvalue via
float&
:Or simply let deduction do its thing: