Created
August 27, 2015 19:09
-
-
Save klemens-morgenstern/b75599292667a4f53007 to your computer and use it in GitHub Desktop.
A simple way to join two arrays constexpr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace detail | |
{ | |
template<std::size_t ... Size> | |
struct num_tuple | |
{ | |
}; | |
template<std::size_t Prepend, typename T> | |
struct appender {}; | |
template<std::size_t Prepend, std::size_t ... Sizes> | |
struct appender<Prepend, num_tuple<Sizes...>> | |
{ | |
using type = num_tuple<Prepend, Sizes...>; | |
}; | |
template<std::size_t Size, std::size_t Counter = 0> | |
struct counter_tuple | |
{ | |
using type = typename appender<Counter, typename counter_tuple<Size, Counter+1>::type>::type; | |
}; | |
template<std::size_t Size> | |
struct counter_tuple<Size, Size> | |
{ | |
using type = num_tuple<>; | |
}; | |
} | |
template<typename T, std::size_t LL, std::size_t RL, std::size_t ... LLs, std::size_t ... RLs> | |
constexpr std::array<T, LL+RL> join(const std::array<T, LL> rhs, const std::array<T, RL> lhs, detail::num_tuple<LLs...>, detail::num_tuple<RLs...>) | |
{ | |
return {rhs[LLs]..., lhs[RLs]... }; | |
}; | |
template<typename T, std::size_t LL, std::size_t RL> | |
constexpr std::array<T, LL+RL> join(std::array<T, LL> rhs, std::array<T, RL> lhs) | |
{ | |
//using l_t = typename detail::counter_tuple<LL>::type; | |
return join(rhs, lhs, typename detail::counter_tuple<LL>::type(), typename detail::counter_tuple<RL>::type()); | |
} | |
int main() | |
{ | |
using namespace std; | |
constexpr std::array<int, 3> l = {1,2,3}; | |
constexpr std::array<int, 3> r = {4,5,6}; | |
constexpr auto s = join(l,r); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In c++20, this can be made simpler :
template<typename T, std::size_t LL, std::size_t RL>
constexpr std::array<T, LL+RL> join(std::array<T, LL> rhs, std::array<T, RL> lhs)
{
std::array<T, LL+RL> ar;
auto current = std::copy(rhs.begin(), rhs.end(), ar.begin());
std::copy(lhs.begin(), lhs.end(), current);
return ar;
}