/* * DiscreteValues_impl.hpp * * Created on: Sep 28, 2011 * Author: heber */ #ifndef DISCRETEVALUE_IMPL_HPP_ #define DISCRETEVALUE_IMPL_HPP_ // include config.h #ifdef HAVE_CONFIG_H #include #endif #include #include "CodePatterns/Assert.hpp" /** Constructor of class DiscreteValue. */ template DiscreteValue::DiscreteValue() : ValueSet(false) {} /** Constructor of class DiscreteValue. */ template DiscreteValue::DiscreteValue(const std::vector &_ValidValues) : ValueSet(false), ValidValues(_ValidValues) {} /** Destructor of class DiscreteValue. */ template DiscreteValue::~DiscreteValue() {} /** Checks whether \a _value is a valid value. * \param _value value to check for validity. * \return true - \a _value is valid, false - is not */ template bool DiscreteValue::isValid(const T &_value) const { const size_t index = findIndexOfValue(_value); if (index == (size_t)-1) return false; else return true; } /** Internal function for finding the index of a desired value. * * \note As this is internal, we do not ASSERT value's presence, but return -1 * such that other functions may ASSERT on that. * * \param _value value to get the index of * \return index such that ValidValues[index] == _value */ template const size_t DiscreteValue::findIndexOfValue(const T &_value) const { size_t index = 0; const size_t max = ValidValues.size(); for (; index < max; ++index) { if (ValidValues[index] == _value) break; } if (index == max) return (size_t)-1; else return index; } /** Adds another value to the valid ones. * * We check whether its already present, otherwise we throw an Assert::AssertionFailure. * * @param _value value to add */ template void DiscreteValue::appendValidValue(const T &_value) { ASSERT(!isValid(_value), "DiscreteValue<>::appendValidValue() - value "+toString(_value)+" is already among the valid"); ValidValues.push_back(_value); } /** Returns all possible valid values. * * @return vector with all allowed values */ template const std::vector &DiscreteValue::getValidValues() const { return ValidValues; } /** Sets the value. * * We check for its validity, otherwise we throw an Assert::AssertionFailure. * * @param _value const reference of value to set */ template void DiscreteValue::set(const T &_value) { const size_t index = findIndexOfValue(_value); ASSERT(index != (size_t)-1, "DiscreteValue<>::set() - value "+toString(_value)+" is not valid."); if (!ValueSet) ValueSet = true; value = index; } /** Getter fot the set value. * * We check whether it has been set, otherwise we throw an Assert::AssertionFailure. * * @return set value */ template const T & DiscreteValue::get() const { ASSERT(ValueSet, "DiscreteValue<>::get() - value has never been set."); return ValidValues[value]; } #endif /* DISCRETEVALUE_IMPL_HPP_ */