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);
}
6
  • Why cant it happen at run time? Also, you might want to look at how C++ templating works (its all compile time based). Commented Jul 4, 2014 at 4:18
  • Exact duplicate of C++ convert integer to string at compile time Commented Jul 4, 2014 at 4:19
  • Whatever it's worth at this point, coliru.stacked-crooked.com/a/b5c4c0c3b63b0c1b Commented Jul 4, 2014 at 4:21
  • @Dgrin91 It totally could happen at run-time, but it would be cool if it didn't have to. Commented Jul 4, 2014 at 4: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". Commented Jul 4, 2014 at 4:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.