Initializing a static char based on template parameter

吃可爱长大的小学妹 提交于 2020-01-07 02:31:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42450025/initializing-a-static-char-based-on-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!