Recently I often encountered the problem, that I had to write a function which takes an input as a const reference. But at some point this function (usually a constructor) calls another function which could use the input as a move reference if possible. For that reason I had to copy the function to allow const reference and move reference, i.e.
#include <iostream>
class A {};
void foo(const A& a) { std::cout << "Reference" << std::endl; }
void foo( A&& a) { std::cout << "Move" << std::endl; }
void bar(const A& a) {
//Other things, which treat "a" as a const reference
foo(std::move(a));
}
void bar(A&& a) {
//Other things, which treat "a" as a const reference
foo(std::move(a));
}
int main() {
A a;
bar(a);
bar(A());
}
However it is obviously pretty ugly to copy bar
two times with the only difference being the signature and the std::move
. One alternative I know would be to make bar
a tempalte function and to use std::forward
, but I don't want to do that because it would allow any parameter type to be passed to bar
(especially since in my real application bar is an implicit constructor).
So my question is: Is there any other way to forward a move reference through a function without writing it twice?
Aucun commentaire:
Enregistrer un commentaire