And I want to make sure template parameter F&& f only accept a non-const lvalue reference.
Then you should not have used a forwarding reference. The whole idea of forwarding is to accept any value category and preserve it for future calls. So the first fix is to not use the wrong technique here, and accept by an lvalue reference instead:
template<typename T, typename F>
inline
auto do_with(T&& rvalue, F& f) {
// As before
}
That should make the compiler complain nicely if you attempt to pass an rvalue into the function. It won't stop the compiler from allowing const lvalues though (F
will be deduced as const F1
). If you truly want to prevent that, you can add another overload:
template<typename T, typename F>
inline
void do_with(T&& , F const& ) = delete;
The parameter type of F const&
will match const lvalues better (and rvalues too, btw), so this one will be picked in overload resolution, and immediately cause an error because its definition is deleted. Non-const lvalues will be routed to the function you want to define.