I'm making a simple constexpr string encoder, see below.
template<char...Chars>
struct encoder
{
constexpr static char encode(char c)
{
return c ^ size;
}
constexpr static size_t size = sizeof...(Chars);
constexpr static const char value[size + 1] = {encode(Chars)...,0};
};
template<typename T,T...Chars>
constexpr auto operator""_encode()
{
return encoder<Chars...>::value;
}
useage:
"aab"_encode
"123"_encode
i want to get char index from encode function,like this
constexpr static char encode(char c,uint32_t index)
{
return c ^ (size + index);
}
or like this
template<uint32_t index>
constexpr static char encode(char c)
{
return c ^ (size + index);
}
But I don't know how. Any one show me how to do that?
You can write the whole thing in a single constexpr function in C++17:
template<typename T, T...Chars>
constexpr auto operator""_encode()
{
constexpr std::size_t size = sizeof...(Chars);
std::array<char, size+1> ret = {}; // Maybe T instead of char?
int i = 0;
((ret[i] = Chars ^ (size + i), i++), ...);
ret[size] = 0;
return ret;
}
(I made it return a std::array instead of a builtin array for everyone's sanity.)
Here's a godbolt link, including one of your test inputs (it helps if you include the desired output, nobody likes poring over ASCII tables and xoring stuff by hand, even if I did that here):
https://godbolt.org/z/P8ABHM
Also, please don't use this to encrypt anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With