如何强制函数只接受左值引用参数 [英] How to force a function to only accept an lvalue reference parameter

查看:24
本文介绍了如何强制函数只接受左值引用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况:

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);
    });
}

我想确保模板参数 F&&f 只接受非const 左值引用.我应该如何强制执行?

I want to make sure the template parameter F&& f only accepts a non-const lvalue reference. How should I enforce this?

推荐答案

我想确保模板参数 F&&f 只接受非常量左值引用.

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
}

如果你试图将一个右值传递给函数,那应该会让编译器很好地抱怨.虽然它不会阻止编译器允许 const 左值(F 将被推导出为 const F1).如果你真的想防止这种情况发生,你可以添加另一个重载:

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;

F const& 的参数类型会更好地匹配 const 左值(顺便说一句,右值也是如此),所以在重载解析中会选择这个,并立即导致错误,因为它的定义被删除.非常量左值将路由到您要定义的函数.

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.

这篇关于如何强制函数只接受左值引用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆