0

I want to do something like this :

template<typename T>
const char * toStr(T num)
{
    thread_local static char rc[someval*sizeof(T)] str = "0x000...\0"; // num of zeros depends on size of T
    // do something with str
    return str;
}

I'm guessing there's some template metaprogramming I'd have to do but I'm not sure where to start.

Edit:

I found a related question here: How to concatenate a const char* in compile time

But I don't want the dependency on boost.

max66
  • 65,235
  • 10
  • 71
  • 111
Mike Lui
  • 1,301
  • 10
  • 23
  • 1. The size should (probably) be `3+2*sizeof(T)`. 2. `\0` in this case adds a second useless null terminator. I don't think you want to have it. 3. I'd say you don't need to initialize the array at all. Just `sprintf` your number into it at each call. 4. Why not use `std::string`s instead of `char` arrays if you're using C++? – HolyBlackCat Feb 25 '17 at 00:26
  • @HolyBlackCat this was just a demonstrative example. 3+2*sizeof(T) is indeed what the current implantation uses for the size. I forgot about the implicit string literal. Thanks for the reminder. I'm using an implementation inspired by this solution: http://stackoverflow.com/a/33447587 because this is a performance sensitive application. The result is copied anyway by the calling function so I dont want the extra string allocation. – Mike Lui Feb 25 '17 at 01:18

1 Answers1

2

Not sure to understand what do you want but... if you want that the str initial value is created compile time and if you accept that toStr() call and helper function (toStrH() in the following example) a C++14 example follows

#include <utility>

template <typename T, std::size_t ... I>
const char * toStrH (T const & num, std::index_sequence<I...> const &)
 {
   static char str[3U+sizeof...(I)] { '0', 'x', ((void)I, '0')..., '\0' };

   // do someting with num

   return str;
 }

template <typename T>
const char * toStr (T const & num)
 { return toStrH(num, std::make_index_sequence<(sizeof(T)<<1U)>{}); }

int main()
 {
   toStr(123);
 }

If you need a C++11 solution, substitute std::make_index_sequence() and std::index_sequence isn't difficult.

max66
  • 65,235
  • 10
  • 71
  • 111