How to generate a constexpr version string from three integers (or perhaps a git/SVN commit/rev. string)?

后端 未结 3 1712
醉酒成梦
醉酒成梦 2020-12-14 12:06

Say I have

constexpr const std::uint8_t major = 1;
constexpr const std::uint8_t minor = 10;
constexpr const std::uint8_t bugfix = 0;

and I

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 12:43

    Here is a C++11 solution. It uses class templates with char... parameter pack to simulate strings:

    #include 
    #include 
    
    template 
    struct String
    {
        static constexpr char value[] = {symbols...};
    };
    
    template 
    constexpr char String::value[];
    
    template 
    struct Concat;
    
    template 
    struct Concat, String>
    {
        using type = String;
    };
    
    template 
    struct Concatenate;
    
    template 
    struct Concatenate
    {
        using type = typename Concat::type>::type;
    };
    
    template <>
    struct Concatenate<>
    {
        using type = String<>;
    };
    
    template 
    struct NumberToString
    {
        using type = typename Concat
            <
                typename std::conditional<(N >= 10), typename NumberToString::type, String<>>::type,
                String<'0' + N % 10>
            >::type;
    };
    
    template <>
    struct NumberToString<0>
    {
        using type = String<'0'>;
    };
    
    constexpr const std::uint8_t major = 1;
    constexpr const std::uint8_t minor = 10;
    constexpr const std::uint8_t bugfix = 0;
    
    using VersionString = Concatenate
        <
            NumberToString::type,
            String<'.'>,
            NumberToString::type,
            String<'.'>,
            NumberToString::type
        >::type;
    
    constexpr const char* version_string = VersionString::value;
    
    int main()
    {
        std::cout << version_string << std::endl;
    }
    

    See live example.

提交回复
热议问题