numb2string
有了上一篇的str2type,类似的可以定义numb2string
1.定义
1 namespace blog 2 { 3 namespace internal{ 4 template< std::size_t N, std::size_t M > 5 constexpr char string_at(const char(&c)[M]) noexcept 6 { 7 static_assert(M <= 101, "String longer than 100 (excluding terminating \\0)!"); 8 return (N < M) ? c[N] : 0; 9 } 10 11 template< char ... Cs > struct string; 12 13 template<> struct string<> {}; 14 15 template< char ... Cs > 16 struct string 17 { 18 static constexpr char const value[sizeof...(Cs)+1] = { Cs...,'\0' }; 19 }; 20 template<char... C> 21 constexpr char const string<C...>::value[sizeof...(C)+1]; 22 } 23 template< char ... Cs > struct string : internal::string< Cs ... > {}; 24 25 namespace internal 26 { 27 template< typename, char ... > 28 struct number_string_builder; 29 30 template< typename T > 31 struct number_string_builder< T > { using type = T; }; 32 template< template< char ... > class S, char ... Hs, char C, char ... Cs > 33 struct number_string_builder< S< Hs ... >, C, Cs ... > 34 : std::conditional< C == 'a', 35 number_string_builder< S< Hs ... > >, 36 number_string_builder< S< C, Hs ...>, Cs ... > >::type { }; 37 38 template< typename, char ... > 39 struct string_builder; 40 template< typename T > 41 struct string_builder< T > { using type = T; }; 42 template< template< char ... > class S, char ... Hs, char C, char ... Cs > 43 struct string_builder< S< Hs ... >, C, Cs ... > 44 : std::conditional< C == '\0', 45 string_builder< S< Hs ... > >, 46 string_builder< S< Hs ..., C >, Cs ... > >::type 47 { }; 48 } 49 }
2.实现
1 #define blog_numb2str(n) \ 2 blog::internal::number_string_builder< blog::internal::string<>, '0' + n%10, \ 3 n/10 == 0 ? 'a' : '0' + (n/10)%10, \ 4 n/100 == 0 ? 'a' : '0' + (n/100)%10, \ 5 n/1000 == 0 ? 'a' : '0' + (n/1000)%10, \ 6 n/10000 == 0 ? 'a' : '0' + (n/10000)%10, \ 7 n/100000 == 0 ? 'a' : '0' + (n/100000)%10, \ 8 n/1000000 == 0 ? 'a' : '0' + (n/1000000)%10, \ 9 n/10000000 == 0 ? 'a' : '0' + (n/10000000)%10, \ 10 n/100000000 == 0 ? 'a' : '0' + (n/100000000)%10, \ 11 n/1000000000 == 0 ? 'a' : '0' + (n/1000000000)%10, \ 12 n/10000000000 == 0 ? 'a' : '0' + (n/10000000000)%10 >::type::value
3.使用
1 std::cout << blog_numb2str(12345678) << std::endl;
4.结果
12345678
5.优缺点