开发者

Expose Member Data Through Read-only Iterator

开发者 https://www.devze.com 2023-04-10 06:43 出处:网络
I have a class \'MyClass\' which contains some data stored in std::maps. The standard maps contain pointers to objects, e.g.

I have a class 'MyClass' which contains some data stored in std::maps. The standard maps contain pointers to objects, e.g.

private:
   std::map<int,Object*> m_data;

I want to expose the data to the outside world but I do not want other classes/functions to be able to modi开发者_如何转开发fy either (i) the map m_data or (ii) the objects pointed to by the values in m_data. I would like some hypothetical function, say getDataBegin() which returns an iterator over the data which has the properties above. For example I want the following pseudo-code examples to fail:

iterator_type itr = myclass.getDataBegin();
erase(itr); // not allowed because we cannot modify m_data;
itr.second = NULL; // not allowed to change content of m_data (falls under first rule)
itr.second->methodWithSideEffect(); // not allowed because changes content of object pointed to.

In short you could say I am after read-only access to some member data. Is this at all possible in a nice way, and if so then how could I go about it?


Try exposing a boost transform_iterator wrapped around the map's const_iterator. The transform function should be something like

[](const pair<int, object*>& x) 
{
    return make_pair(x.first, const_cast<const object*>(x.second));
}


return a const_iterator, const_iterator allows read only access.

std::map<int,Object*>::const_iterator const getDataBegin();
0

精彩评论

暂无评论...
验证码 换一张
取 消