Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index from fold expression

Tags:

c++

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?

like image 291
aaaa Avatar asked Oct 31 '25 04:10

aaaa


1 Answers

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.

like image 99
Max Langhof Avatar answered Nov 02 '25 20:11

Max Langhof