如果您只想一次操作一个字符,那么很容易:
template<char c> struct add_three {
enum { value = c+3 };
};
template <char... Chars> struct EncryptCharsA {
static const char value[sizeof...(Chars) + 1];
};
template<char... Chars>
char const EncryptCharsA<Chars...>::value[sizeof...(Chars) + 1] = {
add_three<Chars>::value...
};
int main() {
std::cout << EncryptCharsA<'A','B','C'>::value << std::endl;
// prints "DEF"
}
CountArgs
是多余的(这就是
sizeof...
是为)而使用的
element-wise transformation of the elements in a parameter-pack
要使转换依赖于以前的结果,一个选项是递归地使用字符,一次使用一个字符,并从中增量地构建一个新模板:
template<char... P> struct StringBuilder {
template<char C> struct add_char {
typedef StringBuilder<P..., C> type;
};
static const char value[sizeof...(P)+1];
};
template<char... P> const char StringBuilder<P...>::value[sizeof...(P)+1] = {
P...
};
template<class B, char...> struct EncryptImpl;
template<class B, char Seed, char Head, char... Tail>
struct EncryptImpl<B, Seed, Head, Tail...> {
static const char next = Head + Seed; // or whatever
typedef typename EncryptImpl<
typename B::template add_char<next>::type,
next, Tail...
>::type type;
};
template<class B, char Seed> struct EncryptImpl<B, Seed> {
typedef B type;
};
template<char... P> struct Encrypt {
typedef typename EncryptImpl<StringBuilder<>, 0, P...>::type type;
};