Files

119 lines
3.0 KiB
C++

/**
* @file include/ActivMiddleware/Misc/TemplateFunctions.h
*
* @brief Header file for miscellaneous template functions with no other home.
*/
#if (!defined ACTIV_MISC_TEMPLATE_FUNCTIONS_H)
#define ACTIV_MISC_TEMPLATE_FUNCTIONS_H
#include "ActivMiddleware/ActivMiddleware.h"
#include "ActivMiddleware/ActivBase/OsException.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include ACTIV_BOOST_INCLUDE(range/iterator_range.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Template function for returning a string from a table.
*
* @param index index into the table of strings @a array.
* @param array table of c strings.
* @param arraySize number of entries in @a array.
*
* @return The entry at index @a index, or if out of bounds, "unknown (0x<index>").
*/
template <typename T>
String IndexToString(const T index, const char * const array[], const size_t arraySize)
{
const size_t actualIndex = static_cast<size_t>(index);
if (actualIndex < arraySize)
return array[actualIndex];
return String("unknown index ") + TypeToString(actualIndex);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Template function to wrap a function call that can throw in a try-catch; the exception is translated to a StatusCode
* if possible.
*
* @param fn the function to be called.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
StatusCode WrapThrowingFunction(const T &fn)
{
try
{
fn();
}
catch (const StatusCodeException &e)
{
return static_cast<StatusCode>(e.m_errorCode);
}
catch(const OsException &e)
{
return OsErrorToStatusCode(e.m_errorCode);
}
ACTIV_CATCH_ALL()
{
return STATUS_CODE_FAILURE;
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Make a single string from a range of strings.
*
* @param range an iterator range of strings.
* @param pFinalSeparator the separator to use between the final two elements, e.g. " and ".
*
* @return A nicely formatted string containing the members of @a range in the format:
* "string1", "string2", "string3""pFinalSeparator""string4"
*/
template<typename RANGE>
const String StringRangeToString(const RANGE &range, const char * const pFinalSeparator)
{
typedef typename Boost::range_iterator<RANGE>::type Iterator;
String output;
for (Iterator iter = Boost::begin(range), end = Boost::end(range); iter != end; ++iter)
{
if (!output.empty())
{
Iterator next = iter;
if ((++next == end) && (0 != pFinalSeparator) && (::strlen(pFinalSeparator) > 0))
{
output.append(pFinalSeparator);
output.append(1, ' ');
}
else
{
output.append(", ");
}
}
output.append(1, '\"');
output.append(*iter);
output.append(1, '\"');
}
return output;
}
} // namespace Activ
#endif // (!defined ACTIV_MISC_TEMPLATE_FUNCTIONS_H)