78 lines
1.6 KiB
C
Raw Normal View History

#pragma once
// std
#include <algorithm>
#include <functional>
#include <type_traits>
// Qt
#include <QtGlobal>
2016-02-27 15:07:23 +01:00
namespace DOS {
template<class Lambda>
2016-03-28 21:36:34 +02:00
struct DeferHelper {
DeferHelper(Lambda lambda)
: m_lambda(std::move(lambda))
{}
~DeferHelper()
{
2016-03-28 21:36:34 +02:00
try {
m_lambda();
} catch (...) {}
}
Lambda m_lambda;
};
template<typename Lambda>
2016-03-28 21:36:34 +02:00
DeferHelper<Lambda> defer(Lambda l)
{
return DeferHelper<Lambda>(std::move(l));
}
template <typename T>
struct wrapped_array {
2016-02-27 15:07:23 +01:00
wrapped_array(T *first, T *last) : begin_ {first}, end_ {last} {}
wrapped_array(T *first, std::ptrdiff_t size)
: wrapped_array {first, first + size} {}
2016-02-27 15:07:23 +01:00
T *begin() const Q_DECL_NOEXCEPT
{
return begin_;
}
T *end() const Q_DECL_NOEXCEPT
{
return end_;
}
T *begin_;
T *end_;
};
template <typename T>
2016-02-27 15:07:23 +01:00
wrapped_array<T> wrap_array(T *first, std::ptrdiff_t size) Q_DECL_NOEXCEPT
{ return {first, size}; }
template <typename T, typename G>
2016-02-27 15:07:23 +01:00
std::vector<T> toVector(G *first, std::ptrdiff_t size) Q_DECL_NOEXCEPT {
const wrapped_array<G> array = wrap_array(first, size);
std::vector<T> result;
2016-01-02 16:48:16 +01:00
for (auto it = array.begin(); it != array.end(); ++it)
result.emplace_back(T(*it));
return result;
}
template <typename T, typename K, typename R = typename std::result_of<K(T)>::type>
2016-02-27 15:07:23 +01:00
std::vector<R> toVector(T *first, std::ptrdiff_t size, K f) Q_DECL_NOEXCEPT {
wrapped_array<T> array = wrap_array<T>(first, size);
std::vector<R> result;
2016-01-02 16:48:16 +01:00
for (auto it = array.begin(); it != array.end(); ++it)
result.emplace_back(R(f(*it)));
return result;
}
2016-01-23 18:40:17 +01:00
}