Here's my situation:
template<typename T, typename F>
inline
auto do_with(T&& rvalue, F&& f) {
auto obj = std::make_unique<T>(std::forward<T>(rvalue));
auto fut = f(*obj);
return fut.then_wrapped([obj = std::move(obj)] (auto&& fut) {
return std::move(fut);
});
}
I want to make sure the template parameter F&& f
only accepts a non-const
lvalue reference. How should I enforce this?
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:
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 asconst F1
). If you truly want to prevent that, you can add another overload: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.You can take
f
by lvalue reference and prevent non-const values withstatic_assert
andis_const
:With the introduction of constraints in C++20, you will be able to use a
requires
clause instead:to add yet another solution
or with SFINAE