首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >区分临时人员和非临时人员的功能签名?

区分临时人员和非临时人员的功能签名?
EN

Stack Overflow用户
提问于 2016-01-09 04:50:45
回答 1查看 79关注 0票数 0

我想要创建一个类栏,可以区分临时人员和非临时人员。根据这个(大约25%下页),如果第二个StealPointer接受const引用(在我的例子中是指向指针),那么我可以不受限制,但是在我的代码中,它只使用StealPointer(Foo*&& foo)版本,而不管它是如何调用的。

代码语言:javascript
复制
class Foo {};

class Bar {
 public:
  // For when StealPointer(new Foo()); is called. Bar instance then owns the
  // pointer.
  void StealPointer(Foo*&& foo) {} // Get the temporaries only.

  // For when a Foo* already exists and is passed in StealPointer(my_foo_ptr);
  // Takes ownership and invalidates the pointer that the caller once had.
  void StealPointer(Foo*&) {} // Get lvalues only.
};

我能做这个吗?是否有一种方法只需要一个函数就可以做到这一点?如果有关系,Bar将将指针存储在unique_ptr中,我希望避免传递unique_ptr或让调用者使用std::move执行操作的额外语法。我不能仅仅通过引用传递指针,因为Foo*类型的临时代码不能转换为Foo*&。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-09 05:15:47

让您的函数模板化,让std::unique_ptr为您担心这些细节。

代码语言:javascript
复制
template <typename Ptr>
void StealPointer(Ptr&& p) // a universal reference, matches *any* type of value
{
    uniqptr = std::move(p); // Works for both rvalues and lvalues
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34689802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档