I wonder how the following can be done
void f(string &&s) { std::string i(move(s)); /* other stuff */ } int main() { std::string s; bind(f, s)(); // Error. bind(f, move(s))(); // Error. bind(f, ref(s))(); // Error. }
How can I pass an rvalue reference and store it as an rvalue reference (possibly wrapped) in the call wrapper? I know I can manually write up a class like std::reference_wrapper
that has a conversion function to T&&
, but I would rather want to avoid that and use Standard technology.
I implemented it like AProgrammer recommends:
template struct adv { T t; explicit adv(T &&t):t(forward(t)) {} template T &&operator()(U &&...) { return forward(t); } }; template adv make_adv(T &&t) { return adv{forward(t)}; } namespace std { template struct is_bind_expression > : std::true_type {}; }
Now I can say
void f(string &&s) { std::string i(move(s)); /* other stuff */ } int main() { std::string s; bind(f, make_adv(move(s)))(); // Works! }
If we pass an lvalue to make_adv
, it will forward it as an lvalue referring to the input argument, so it can be used as a replacement for std::ref
, in this case.
My take on this.
20.8.10.1.2/10 in N3225
The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows:
- if TiD is reference_wrapper, the argument is tid.get() and its type Vi is T&;
- if the value of is_bind_expression::value is true, the argument is tid(std::forward(uj)...) and its type Vi is result_of::type;
- if the value j of is_placeholder::value is not zero, the argument is std::forward(uj) and its type Vi is Uj&&;
- otherwise, the value is tid and its type Vi is TiD cv &.
So the only possibility to have a rvalue reference is to have is_bind_expression::value
true or is_placeholder::value
not zero. The second possibility has implications you don't want and achieving the wanted result with the first would imply that the problem we are trying to solve is solved if we restrict to the standard provided types. So, the only possibility would be to provide your own wrapper and a specialisation for is_bind_expression
(that is allowed by 20.8.10.1.1/1) as I don't see one.
How can I pass an rvalue reference and store it as an rvalue reference in the call wrapper?
The problem here is that such a bind function object can be invoked multiple times. If the function object forwarded a bound parameter as rvalue this would obviously only work once. So, this is a bit of a safety issue.
But in some cases this kind of forwarding is exactly what you want. You could use a lambda as an intermediary:
bind([](string& s){f(move(s));},move(s));
Basically, I came up with this bind+lambda combination as a workaround for a missing "move-capture".
You can use a mutable lambda object.
auto func = [=]() mutable { f(std::move(s)); };