fork(3) download
  1. #include <iostream>
  2. #include <array>
  3. #include <utility>
  4. #include <cstring>
  5.  
  6. namespace detail
  7. {
  8. template <typename C, std::size_t N, std::size_t...Is>
  9. constexpr std::array<C, sizeof...(Is) + 1> truncate(const C(&s)[N], std::index_sequence<Is...>)
  10. {
  11. return {(Is < N ? s[Is] : 0)..., 0};
  12. }
  13.  
  14. }
  15.  
  16. template <std::size_t L, typename C, std::size_t N>
  17. constexpr std::array<C, L + 1> truncate(const C(&s)[N])
  18. {
  19. return detail::truncate(s, std::make_index_sequence<L>{});
  20. }
  21.  
  22. #define SOMETEXT "example"
  23. #define limit 8
  24.  
  25. int main()
  26. {
  27. constexpr auto text8 = truncate<limit>(SOMETEXT);
  28. std::cout << "text = " << text8.data() << std::endl;
  29. std::cout << "len(text) = " << strlen(text8.data()) << " <= " << limit << std::endl;
  30. constexpr auto text4 = truncate<4>(SOMETEXT);
  31. std::cout << "text = " << text4.data() << std::endl;
  32. std::cout << "len(text) = " << strlen(text4.data()) << " <= " << 4 << std::endl;
  33. }
  34.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
text = example
len(text) = 7 <= 8
text = exam
len(text) = 4 <= 4