[英]C++ Passing a member variable to a member class
I have legacy code where a similar method is used to cycle through a sequential container (vector in this example. Some implementations use other kinds of containers). 我有一些遗留代码,其中使用类似的方法循环遍历顺序容器(在本示例中为向量。某些实现使用其他种类的容器)。 So I factored it out into a template so I could reuse the same piece of code for any container type. 因此,我将其分解为模板,以便可以对任何容器类型重用同一段代码。
template<template<class, class> class TContainer, class TObject>
class cycle
{
public:
explicit cycle( TContainer<TObject, std::allocator<TObject>> & container )
: mContainer( container ), index(0) {}
TObject getNext(int numObjectsToCycle)
{ return mContainer[index++ % numObjectsToCycle]; }
private:
TContainer<TObject, std::allocator<TObject>> & mContainer;
int index;
};
Then my class has a cycler to cycle through my variable numbers. 然后,我班上有一个循环仪,循环显示我的变量号。
class myClass
{
std::vector<int> numbers;
public:
cycle<vector, int> cycler;
// Is it safe to pass numbers since it is declared first??
myClass() : cycler(numbers) {}
};
Then, I use the code like below.: 然后,我使用如下代码:
myObject.cycler.getNext(size);
Is it a good programming practice to pass the vector "numbers" to cycler? 将向量“数字”传递给循环程序是一种好的编程习惯吗? Is there a better way of implementing my template? 有没有更好的方法来实现我的模板?
The code really is to be able to infinitely loop through objects. 该代码实际上是要能够无限循环地遍历对象。 My class is invoked from external code that just calls a member method, and I want to be able to just call getNext() so I wouldn't have to use an index. 我的类是从仅调用成员方法的外部代码中调用的,并且我希望能够仅调用getNext(),因此不必使用索引。
In the standard library another "pattern" exists and it's the iterator pattern . 在标准库中,存在另一个“模式”,它是迭代器模式 。 Basically every container type implements begin
and end
which returns, respectively, the iterator to the first element and the past-the-end element (which is always guaranteed to exists). 基本上,每种容器类型都实现begin
和end
,它们分别将迭代器返回到第一个元素和past-the-end元素(始终保证存在)。
This works for every container type, from std::vector
to std::array
including C-style arrays with std::begin
and std::end
. 这适用于每种容器类型,从std::vector
到std::array
包括带有std::begin
和std::end
C样式数组。 If you want to loop in a generic container you can do, for example: 如果要在通用容器中循环,可以执行以下操作:
template<typename Container>
void cicle(Container const& c) {
for (auto const& i : c) {
// …
}
}
or, to better visualize the pattern: 或者,以更好地形象化模式:
template<typename Container>
void cicle(Container const& c) {
for (auto it = std::begin(c); it != std::end(c); ++it) {
// …
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.