Skip to content

Instantly share code, notes, and snippets.

@Seikilos
Last active August 29, 2015 14:00
Show Gist options
  • Save Seikilos/11221161 to your computer and use it in GitHub Desktop.
Save Seikilos/11221161 to your computer and use it in GitHub Desktop.
Generic Stepper Class (requires C++11 features, >=VS2013)
#pragma once
#include <functional>
#include <assert.h>
namespace Utils
{
/**
* Provides arbitrary stepping functionality with a custom property type
*/
template<typename TFunc>
class Stepper
{
public:
typedef std::function<TFunc> StepType;
Stepper(){ Reset(); }
/**
* Adds step but resets the position of stepper
*/
void AddStep(StepType t) { m_vSteps.push_back(t); Reset(); }
void Reset() { m_iterPosition = m_vSteps.begin(); }
void Advance()
{
++m_iterPosition;
if (m_iterPosition == m_vSteps.end())
{
Reset();
}
}
template<typename... Arguments>
void Execute(Arguments... args)
{
#ifdef _DEBUG
assert(m_iterPosition != m_vSteps.end());
#endif
(*m_iterPosition)(args...);
}
private:
std::vector<StepType> m_vSteps;
typename std::vector<StepType>::iterator m_iterPosition;
};
}
#include "Stepper.hpp"
using namespace Utils;
void test_stepper()
{
Stepper<void(bool, int)> st;
int pos = 0;
st.AddStep([&](bool b, int i) {++pos; });
st.AddStep([&](bool b, int i) {pos = i; });
assert(pos == 0);
st.Execute(true, 42);
assert(pos == 1);
st.Advance();
st.Execute(true, 42);
assert(pos == 42);
st.Advance();
st.Execute(true, 42);
assert(pos == 43);
st.Reset();
st.Execute(true, 42);
assert(pos == 44);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment