如何从折叠表达式中获取索引

How to get index from fold expression

本文关键字:获取 索引 表达式 折叠      更新时间:2023-10-16

我正在制作一个简单的constexpr字符串编码器,见下文。

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;
}

用途:

"啊"_encode

"123"_encode

我想从编码函数中获取字符索引,像这样

constexpr static char encode(char c,uint32_t index)
{
return c ^ (size + index);
}

或者像这样

template<uint32_t index>
constexpr static char encode(char c)
{
return c ^ (size + index);
}

但我不知道怎么做。有人告诉我怎么做吗?

您可以在 C++17 中的单个constexpr函数中编写整个内容:

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;
}

(为了每个人的理智,我让它返回一个std::array而不是一个内置数组。

这是一个 godbolt 链接,包括您的一个测试输入(如果您包含所需的输出会有所帮助,没有人喜欢仔细研究 ASCII 表并手动xor东西,即使我在这里这样做(:

https://godbolt.org/z/P8ABHM

另外,请不要使用它来加密任何东西。