mardi 4 août 2015

Compiler error when passing rvalue reference through variadic templates

There is a requirement where I need to pass an rvalue from 1 function to another function via variadic template. To avoid real code complexity, minimal example is below using int:

void Third (int&& a)
{}

template<typename... Args>
void Second (Args&&... args) {
  Third(args...);
}

void First (int&& a) {
  Second(std::move(a));  // error: cannot bind ‘int’ lvalue to ‘int&&’
  Third(std::move(a));  // OK
}

int main () {
  First(0);
}

First(0) is called properly. If I invoke Third(int&&) directly then it works fine using std::move(). But calling Second(Args&&...) results in:

error: cannot bind ‘int’ lvalue to ‘int&&’
   Third(args...);        ^
note:   initializing argument 1 of ‘void Third(int&&)’
 void Third (int&& a)

What is the correct way to achieve the successful compilation for Second(Args&&...)?

FYI: In real code the Second(Args&&...) is mix of lvalues, rvalues and rvalue references. Hence if I use:

Third(std::move(args...));

it works. But when there are mix of arguments, it has problems.

Aucun commentaire:

Enregistrer un commentaire