I'm trying to implement a template that takes a container as parameter. The template has a getnext
method that cycles through the elements in the parameter. Take note that I'm not using C++11.
Header:
#pragma once
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;
};
Implementation:
#include <iostream>
#include <vector>
#include "cycle.h"
using namespace std;
class Processor
{
int mIndex;
vector<int> numbers;
public:
cycle<vector, int> cycler;
// Is it safe to pass numbers since it is declared first??
Processor() : mIndex(0), cycler(numbers) {}
void update() { cout << numbers[mIndex++ % numbers.size()] << std::endl;}
void addNumber(int x) { numbers.push_back(x); }
};
int main()
{
Processor S;
for (int i = 0; i < 5; ++i)
{
S.addNumber(i+1);
}
cout << "using update" << endl;
for (int c = 0; c < 10; ++c)
{
S.update();
}
cout << "using cycle" << endl;
for (int c = 0; c < 10; ++c)
{
cout << S.cycler.getNext(5) << endl;
}
std::cin.get();
}
Any improvement or potential issues to the code?