fork(1) download
  1. #include <array>
  2. #include <cstddef>
  3. #include <cstring>
  4.  
  5. namespace my
  6. {
  7.  
  8. namespace detail
  9. {
  10.  
  11. template <typename CharT>
  12. constexpr auto
  13. strlen_c(const CharT *const string) noexcept
  14. {
  15. auto count = static_cast<std::size_t>(0);
  16. for (auto s = string; *s; ++s)
  17. ++count;
  18. return count;
  19. }
  20.  
  21. template <std::size_t N, std::size_t M, typename CharT>
  22. struct truncation_helper
  23. {
  24. template <typename... CharTs>
  25. static constexpr auto
  26. help(const CharT *const string, const std::size_t length, const CharTs... chars) noexcept
  27. {
  28. static_assert(sizeof...(chars) == M, "wrong instantiation");
  29. const auto c = (length > M) ? string[M] : static_cast<CharT>(0);
  30. return truncation_helper<N, M + 1, CharT>::help(string, length, chars..., c);
  31. }
  32. };
  33.  
  34. template <std::size_t N, typename CharT>
  35. struct truncation_helper<N, N, CharT>
  36. {
  37. template <typename... CharTs>
  38. static constexpr auto
  39. help(const CharT *, const std::size_t, const CharTs... chars) noexcept
  40. {
  41. static_assert(sizeof...(chars) == N, "wrong instantiation");
  42.  
  43. std::array<CharT, N + 1> result = { chars..., static_cast<CharT>(0) };
  44. return result;
  45. }
  46. };
  47.  
  48. } // namespace detail
  49.  
  50. template <std::size_t N, typename CharT>
  51. constexpr auto
  52. truncate(const CharT *const string) noexcept
  53. {
  54. const auto length = detail::strlen_c(string);
  55. return detail::truncation_helper<N, 0, CharT>::help(string, length);
  56. }
  57.  
  58. } // namespace my
  59.  
  60. #ifndef SOMETEXT
  61. # define SOMETEXT "example"
  62. #endif
  63.  
  64. namespace /* anonymous */
  65. {
  66. constexpr auto limit = static_cast<std::size_t>(8);
  67. constexpr auto text = my::truncate<limit>(SOMETEXT);
  68. }
  69.  
  70. int
  71. main()
  72. {
  73. std::printf("text = \"%s\"\n", text.data());
  74. std::printf("len(text) = %lu <= %lu\n", std::strlen(text.data()), limit);
  75. std::printf("text = \"%s\"\n", my::truncate<4>(SOMETEXT).data());
  76. }
  77.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
text = ""
len(text) = 0 <= 8
text = "exam"