Compile-time 'String' Manipulation with Variadic Templates

后端 未结 2 1294
忘掉有多难
忘掉有多难 2020-12-30 10:04

Hey all, I\'m currently trying to write a compile-time string encryption (using the words \'string\' and \'encryption\' quite loosely) lib.

What I have so far is as

2条回答
  •  死守一世寂寞
    2020-12-30 11:08

    If you just want to operate on one character at a time its easy:

    template struct add_three {
        enum { value = c+3 };
    };
    
    template  struct EncryptCharsA {
        static const char value[sizeof...(Chars) + 1];
    };
    
    template
    char const EncryptCharsA::value[sizeof...(Chars) + 1] = {
        add_three::value...
    };
    
    int main() {   
        std::cout << EncryptCharsA<'A','B','C'>::value << std::endl;
        // prints "DEF"
    }
    

    Note that CountArgs is redundant (that's what sizeof... is for) and that this uses element-wise transformation of the elements in a parameter-pack.


    To make the transformation dependent on previous results, one option would be to consume the characters recursively, one at a time, and incrementally build a new template from that:

    template struct StringBuilder {
        template struct add_char {
            typedef StringBuilder type;
        };
    
        static const char value[sizeof...(P)+1];
    };
    
    template const char StringBuilder::value[sizeof...(P)+1] = {
        P...
    };
    
    template struct EncryptImpl;
    
    template 
    struct EncryptImpl {
        static const char next = Head + Seed; // or whatever
        typedef typename EncryptImpl<
            typename B::template add_char::type,
            next, Tail...
        >::type type;
    };
    
    template struct EncryptImpl {
        typedef B type;
    };
    
    template struct Encrypt {
        typedef typename EncryptImpl, 0, P...>::type type;
    };
    

提交回复
热议问题