如何迭代(在类之外)作为向量的私有成员(unique_ptr< T>)。 [英] How to iterate (outside a class) a private member which is a vector<unique_ptr<T>>

查看:54
本文介绍了如何迭代(在类之外)作为向量的私有成员(unique_ptr< T>)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Organization {
 private:
  vector<unique_ptr<Employee>> employees_;
  vector<unique_ptr<Item>> items_;
}org;

我需要在课堂外使用一种设施来遍历员工和物品并打电话给他们的成员,类似于以下内容...

I need to have a facility outside the class to iterate over the employees and items and call their members, like the following...

for(auto const& e : getEmployees()) { e.get()->getName(); } 

但是我不能创建 getEmployees()函数返回 employees _ ,因为unique_ptrs的向量不可复制

But I cannot make getEmployees() function to return employees_, as vector of unique_ptrs is not copyable

所以目前我正在使用for_each_employee函数

So currently I'm having a for_each_employee function

template<class callable>
void Organization::for_each_employee(callable f) {
     for(auto const& e : employees_) {
        f(e.get());
   }
}

// And I use it like,
org.for_each_employee([](Employee* e){ e->getName(); });

但是我不喜欢这个想法,因为我必须写for_each_employee和for_each_item。我有其他类似结构的类。因此,我最终将编写许多for_each_XX类型的函数。这不是我想要的。

But I do not like this idea as I'll have to write for_each_employee and for_each_item. I have similar other classes of the similar structure. So I will end up writing lot of for_each_XX type functions. This is not what I want.

我可以拥有属于这些类的朋友的通用for_each函数(例如,包含unique_ptrs向量的Organization)吗?

Can I have generic for_each function that are friends of these classes (like Organization that contain vector of unique_ptrs)?

如何(在类外部)迭代作为 vector< unique_ptr< T>>

How to iterate (outside a class) a private member which is a vector<unique_ptr<T>>

推荐答案

最简单易读的方法是提供一种访问方法,该访问方法将可能是 const 限定引用的返回给数据成员。这样,您就不会尝试复制不可复制的成员。

The simplest and quite readable approach is to provide an access method that returns a possibly const-qualified reference to the data member. This way, you don't try to copy non-copyable members.

const vector<unique_ptr<Item>>& getItems()
{
    return items_;
}

可以这样使用

for (const auto& item : organizationInstance.getItems())
    item->doStuff();

这篇关于如何迭代(在类之外)作为向量的私有成员(unique_ptr&lt; T&gt;)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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