根据模板参数初始化静态字符

根据模板参数初始化静态字符

本文介绍了根据模板参数初始化静态字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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.

我在这里找到了一个相关的问题:如何连接一个编译时为const char *

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

但是我不想依赖于升压.

But I don't want the dependency on boost.

推荐答案

不确定要了解什么,但是...如果要创建 str 初始值,则是否需要编译?您接受 toStr()调用和帮助函数(在下面的示例中为 toStrH()),然后是C ++ 14示例

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);
 }

如果您需要C ++ 11解决方案,则用 std :: make_index_sequence() std :: index_sequence 并不困难.

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

这篇关于根据模板参数初始化静态字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 00:16