Concatenate compile-time strings in a template at compile time?

前端 未结 3 1730
猫巷女王i
猫巷女王i 2020-12-08 12:47

Currently I have:

template  struct typename_struct {
    static char const* name() { 
        return (std::string(typename_struc         


        
3条回答
  •  广开言路
    2020-12-08 13:17

    Alternative way without using recursive templates (but requires C++14):

    #include 
    template using is      = std::integer_sequence;
    template   using make_is = std::make_integer_sequence;
    
    constexpr auto size(const char*s) { int i = 0; while(*s!=0){++i;++s;} return i; }
    
    template
    struct concat_impl;
    
    template
    struct concat_impl, S2, is> {
        static constexpr const char value[]
        {
            S1[I1]..., S2[I2]..., 0
        };
    };
    
    template
    constexpr auto concat {
        concat_impl, S2, make_is>::value
    };
    

    Example:

    constexpr const char a[] = "int";
    constexpr const char c[] = "**";
    
    #include 
    int main()
    {
        std::cout << concat << '\n';
    }
    

    append characters to string can also be implemented like this, by replacing the second const char* parameter with char....

提交回复
热议问题