I wanted to have integers converted to string literals at compile time in C++17. I used this perfect solution.
Anyways, the problem with this solution is that I am not able to assign the result of num_to_string
to a constexpr char []
:
static constexpr const char number_str[] = num_to_string<5683>::value; // ERROR
The error is:
error: initializer fails to determine size of ‘number_str’
error: array must be initialized with a brace-enclosed initializer
I solved the problem in such a way that I ignored "my requirement" that the number_str
must be an array so I've made it a pointer:
static constexpr const char *number_str{detail::num_to_string<5683>::value};
And that's all good, BUT: :)
I'm still curious to see whether it is possible, so my idea is to somehow copy-assign an array to another one.
Having an array and pointers:
static constexpr char first_array[] = "aaaabbbbcccc";
I would like to copy initialize the second array, like that:
static constexpr char second_array[] = copy_the(first_array);
- I can't do it using function templates, because functions can't return C-arrays.
- Using
structs
for folding the arrays will result in returning an object, which could be then assigned to the array, but you can't copy-assign arrays. - I tried to use fold expressions with template aliases and with
std::integer_sequence
, e.g.:
template <auto Ptr, std::size_t... I>
using explode_array_impl = (Ptr[I], ...);
template <auto Ptr, std::size_t N>
using explode_array = explode_array_impl<Ptr, std::make_index_sequence<N>>;
But it won't work because a template alias expects type-id
on the right side of =
.
Is there a way to make it possible to somehow copy-assign an array to another one?