使用Variadic模板编译时"字符串"操作

Rap*_*tor 8 c++ templates metaprogramming c++11

嘿所有,我目前正在尝试编写一个编译时字符串加密(使用"字符串"和"加密"字样很松散)lib.

我到目前为止的内容如下:

// Cacluate narrow string length at compile-time
template <char... ArgsT>
struct CountArgs
{
 template <char... ArgsInnerT> struct Counter;

 template <char Cur, char... Tail>
 struct Counter<Cur, Tail...>
 {
  static unsigned long const Value = Counter<Tail...>::Value + 1;
 };

 template <char Cur>
 struct Counter<Cur>
 {
  static unsigned long const Value = 1;
 };

 static unsigned long const Value = Counter<ArgsT...>::Value;
};

// 'Encrypt' narrow string at compile-time
template <char... Chars>
struct EncryptCharsA
{
 static const char Value[CountArgs<Chars...>::Value + 1];
};

template<char... Chars>
char const EncryptCharsA<Chars...>::Value[CountArgs<Chars...>::Value + 1] =
{
 Chars...
};
Run Code Online (Sandbox Code Playgroud)

但是当我将它们扩展到静态数组时,我无法弄清楚如何对字符执行操作.我只想对每个字符执行一个简单的操作(例如'(((c ^ 0x12)^ 0x55)+ 1)',其中c是字符).

向正确的方向推动将非常感激.

谢谢大家.

Geo*_*che 6

如果您只想一次操作一个字符,这很容易:

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"
}
Run Code Online (Sandbox Code Playgroud)

请注意,这CountArgs是多余的(这就是为什么sizeof...),并且这使用了 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;
};
Run Code Online (Sandbox Code Playgroud)