Advertisement
kenpusney

compile time array concat

Aug 26th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <iterator>
  2. #include <algorithm>
  3. #include <array>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. namespace impl {
  9.  
  10.     template<class T, size_t N1, size_t N2>
  11.     array<T, N1 + N2>
  12.     constexpr operator >>(const array<T, N1>& array1, const array<T, N2>& array2) {
  13.         array<T, N1 + N2> result {};
  14.  
  15.         copy(array1.begin(), array1.end(), result.begin());
  16.         copy(array2.begin(), array2.end(), result.begin() + array1.size());
  17.         return result;
  18.     }
  19.  
  20.     template<class... Args>
  21.     constexpr auto concat(Args&&... args) {
  22.         return (... >> args);
  23.     }
  24. }
  25.  
  26. using impl::concat;
  27.  
  28. int main() {
  29.     constexpr array a {1, 2, 3, 4};
  30.     constexpr array b {4, 5, 6};
  31.  
  32.     constexpr auto a_and_b = concat(a, b, a, b);
  33.  
  34.     static_assert(a_and_b.size() == 14);
  35.     static_assert(a_and_b[5] == 5);
  36.     static_assert(a_and_b[12] == 5);
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement