I am trying to figure out why the captured variable cannot be passed to the foo function by reference, the program shown below does not compile with the following error:
error: invalid initialization of reference of type
'Object&' from expression of type 'const Object'
Is there some way to perfect forward the universal reference into the lambda so that it is captured by reference for later use? Types T might also be R-Values or a combination of R-Values and L-Values, so they cannot always be captured by reference.
struct Object
{
};
void foo(Object& a)
{
}
template<typename... T>
auto bar(T&&... values)
{
return [values...](){
foo(values...);
};
}
int main ()
{
Object obj;
auto lambda = bar(obj);
return 0;
}
You're by capturing by values which stores values as const members inside the closure, and they cannot bind to non-const lvalue references. For capture by-ref you've forgot to put '&' before values:
A small example.
The only diff between the two files:
Compile the one with by-value capture:
Compile the other: