如何使模板右值引用参数ONLY绑定到右值引用? [英] How to make template rvalue reference parameter ONLY bind to rvalue reference?

查看:212
本文介绍了如何使模板右值引用参数ONLY绑定到右值引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写网络库,并大量使用move语义来处理文件描述符的所有权。我的一个类希望接收其他类型的文件描述符封装,并取得所有权,因此它是像

I'm writing a network library and use move semantics heavily to handle ownership for file descriptors. One of my class wishes to receive file descriptor wrappers of other kinds and take ownership, so it's something like

struct OwnershipReceiver
{
  template <typename T>
  void receive_ownership(T&& t)
  {
     // taking file descriptor of t, and clear t
  }
};

它必须处理多个不相关的类型,所以receive_ownership必须是一个模板,希望它只绑定到右值引用,所以当传递一个左值时,用户必须显式声明std :: move。

It has to deal multiple unrelated types so receive_ownership has to be a template, and to be safe, I wish it ONLY binds to rvalue references, so that user has to explicitly state std::move when passing an lvalue.

receive_ownership move(some_lvalue));

但问题是:C ++模板扣除允许传递一个左值而不需要额外的努力。我实际上在脚上自拍了一次,偶然地将一个左值传递给receive_ownership,然后使用那个左值(清除)。

But the problem is: C++ template deduction allows an lvalue to be passed in without extra effort. And I actually shot myself on the foot once by accidentally passing an lvalue to receive_ownership and use that lvalue(cleared) later.

这里是问题:模板只能绑定到右值引用?

So here is the question: how to make a template ONLY bind to rvalue reference?

推荐答案

可以限制 T 不是一个左值引用,因此防止lval值绑定到它:

You can restrict T to not be an lvalue reference, and thus prevent lvalues from binding to it:

#include <type_traits>

struct OwnershipReceiver
{
  template <typename T,
            class = typename std::enable_if
            <
                !std::is_lvalue_reference<T>::value
            >::type
           >
  void receive_ownership(T&& t)
  {
     // taking file descriptor of t, and clear t
  }
};

这可能是一个好主意,添加某种限制到 T ,以便它只接受文件描述符封装。

It might also be a good idea to add some sort of restriction to T such that it only accepts file descriptor wrappers.

这篇关于如何使模板右值引用参数ONLY绑定到右值引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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