3

In the following example I use snprintf inside a template function to create a string that contains the value of the template parameter N. I would like to know if there is a way to generate this string at compile time instead.

template <unsigned N>
void test()
{
    char str[8];
    snprintf(str, 8, "{%d}", N);
}
Chris_F
  • 4,991
  • 5
  • 33
  • 63
  • Why cant it happen at run time? Also, you might want to look at how C++ templating works (its all compile time based). – David says Reinstate Monica Jul 04 '14 at 04:18
  • Exact duplicate of [C++ convert integer to string at compile time](http://stackoverflow.com/questions/6713420/c-convert-integer-to-string-at-compile-time) – metacubed Jul 04 '14 at 04:19
  • Whatever it's worth at this point, http://coliru.stacked-crooked.com/a/b5c4c0c3b63b0c1b – chris Jul 04 '14 at 04:21
  • @Dgrin91 It totally could happen at run-time, but it would be cool if it didn't have to. – Chris_F Jul 04 '14 at 04:35
  • @metacubed It's not really an exact duplicate. I'm looking a string that contains more than just the number. Look at the code and see the format string. `"{%d}"` not `"%d"`. – Chris_F Jul 04 '14 at 04:40
  • @Chris_F the linked question describes a macro - you can put any extra characters in there as per your needs. Even the scenario of the question (a template parameter) is the same. I could change my comment to "almost duplicate" if you like... :) – metacubed Jul 04 '14 at 04:50

1 Answers1

5

After a bit more digging around I came across this on SO: https://stackoverflow.com/a/24000041/897778

Adapted for my use case I get:

namespace detail
{
    template<unsigned... digits>
    struct to_chars { static const char value[]; };

    template<unsigned... digits>
    const char to_chars<digits...>::value[] = {'{', ('0' + digits)..., '}' , 0};

    template<unsigned rem, unsigned... digits>
    struct explode : explode<rem / 10, rem % 10, digits...> {};

    template<unsigned... digits>
    struct explode<0, digits...> : to_chars<digits...> {};
}

template<unsigned num>
struct num_to_string : detail::explode<num / 10, num % 10>
{};

template <unsigned N>
void test()
{
    const char* str = num_to_string<N>::value;
}

boost::mpl was also suggested, but this code seems simpler.

Community
  • 1
  • 1
Chris_F
  • 4,991
  • 5
  • 33
  • 63