Select Git revision
CastArray.hpp
Stéphane Del Pino authored
Remove almost all std::exit calls. Now, one should use one of the provided exceptions. - NormalError: an error which is related to the use of the code. It is not related to a bug - NotImplementedError: an error related to a functionnality that is not avaliable yet - UnexpectedError: an error related to some unexpected state. This is related to a bug Closes #13
CastArray.hpp 2.50 KiB
#ifndef CAST_ARRAY_HPP
#define CAST_ARRAY_HPP
#include <Array.hpp>
#include <PugsTraits.hpp>
#include <iostream>
#include <Exceptions.hpp>
template <typename DataType, typename CastDataType>
class CastArray
{
public:
using data_type = CastDataType;
private:
const Array<DataType> m_array;
const size_t m_size;
CastDataType* const m_values;
public:
PUGS_INLINE
const size_t&
size() const
{
return m_size;
}
PUGS_INLINE
CastDataType& operator[](const size_t& i) const
{
Assert(i < m_size);
return m_values[i];
}
PUGS_INLINE
CastArray& operator=(const CastArray&) = default;
PUGS_INLINE
CastArray& operator=(CastArray&&) = default;
PUGS_INLINE
CastArray() : m_size(0), m_values(nullptr)
{
;
}
PUGS_INLINE
CastArray(const Array<DataType>& array)
: m_array(array),
m_size(sizeof(DataType) * array.size() / sizeof(CastDataType)),
m_values((array.size() == 0) ? nullptr : reinterpret_cast<CastDataType*>(&(array[0])))
{
static_assert((std::is_const_v<CastDataType> and std::is_const_v<DataType>) or (not std::is_const_v<DataType>),
"CastArray cannot remove const attribute");
if (sizeof(DataType) * array.size() % sizeof(CastDataType)) {
throw UnexpectedError("cannot cast array to the chosen data type");
}
}
PUGS_INLINE
CastArray(DataType& value)
: m_size(sizeof(DataType) / sizeof(CastDataType)), m_values(reinterpret_cast<CastDataType*>(&(value)))
{
static_assert((std::is_const_v<CastDataType> and std::is_const_v<DataType>) or (not std::is_const_v<DataType>),
"CastArray cannot remove const attribute");
static_assert(is_trivially_castable<DataType>, "Defining CastArray from non trivially castable type is not "
"allowed");
}
PUGS_INLINE
CastArray(DataType&& value) = delete;
PUGS_INLINE
CastArray(const CastArray&) = default;
PUGS_INLINE
CastArray(CastArray&&) = default;
PUGS_INLINE
~CastArray() = default;
};
template <typename CastDataType>
struct cast_array_to
{
template <typename DataType>
PUGS_INLINE static CastArray<DataType, CastDataType>
from(const Array<DataType>& array)
{
return CastArray<DataType, CastDataType>(array);
}
};
template <typename CastDataType>
struct cast_value_to
{
template <typename DataType>
PUGS_INLINE static CastArray<DataType, CastDataType>
from(DataType& value)
{
return CastArray<DataType, CastDataType>(value);
}
};
#endif // CAST_ARRAY_HPP