如何在不公开所使用的容器的情况下公开迭代器?
我已经使用 C# 一段时间了,回到 C++ 很头疼。 我正在尝试将我的一些实践从 C# 转移到 C++,但我发现了一些阻力,我很乐意接受您的帮助。
我想为这样的类公开一个迭代器:
template <class T>
class MyContainer
{
public:
// Here is the problem:
// typedef for MyIterator without exposing std::vector publicly?
MyIterator Begin() { return mHiddenContainerImpl.begin(); }
MyIterator End() { return mHiddenContainerImpl.end(); }
private:
std::vector<T> mHiddenContainerImpl;
};
我正在尝试一些不是问题的事情吗? 我应该输入 def std::vector< 吗? T >::迭代器? 我希望只依赖于迭代器,而不是实现容器......
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.
I would like to expose an iterator for a class like this:
template <class T>
class MyContainer
{
public:
// Here is the problem:
// typedef for MyIterator without exposing std::vector publicly?
MyIterator Begin() { return mHiddenContainerImpl.begin(); }
MyIterator End() { return mHiddenContainerImpl.end(); }
private:
std::vector<T> mHiddenContainerImpl;
};
Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能会发现以下文章很有趣,因为它恰好解决了您发布的问题:关于对象之间的张力 - C++ 中的面向通用编程以及类型擦除可以做什么
You may find the following article interesting as it addresses exactly the problem you have posted: On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It
我之前已经完成了以下操作,以便获得一个独立于容器的迭代器。 这可能有点过头了,因为我也可以使用一个 API,其中调用者传入一个向量&,该向量应该填充所有元素,然后调用者可以从直接向量。
I have done the following before so that I got an iterator that was independent of the container. This may have been overkill since I could also have used an API where the caller passes in a
vector<T*>&
that should be populated with all the elements and then the caller can just iterate from the vector directly.这应该可以满足您的要求:
来自 Accelerated C++:
This should do what you want:
From Accelerated C++:
我不确定你所说的“不公开 std::vector”是什么意思,但实际上,你可以这样定义你的 typedef:
稍后你将能够更改这些 typedef,而用户不会注意到任何事情......
顺便说一句,如果您希望您的类充当容器,那么公开一些其他类型被认为是很好的做法:
如果您的类需要:
您将在这里找到所有这些 typedef 的含义: 关于向量的 STL 文档
编辑:添加了评论中建议的
typename
I am unsure about what you mean by "not exposing std::vector publicly" but indeed, you can just define your typedef like that:
You will be able to change these typedefs later without the user noticing anything ...
By the way, it is considered good practice to also expose a few other types if you want your class to behave as a container:
And if needed by your class:
You'll find the meaning of all these typedef's here: STL documentation on vectors
Edit: Added the
typename
as suggested in the comments