【发布时间】:2017-02-26 04:51:32
【问题描述】:
我设法解决了之前关于初始化静态 char 数组的问题,在这里问:Initializing a static char based on template parameter
我不喜欢我的解决方案中需要辅助功能:
//static char arr[N] = {[0]='0', [1]='x', [N-1]='\0',};
// ideally want this, but not currently implemented in g++
template <char... chars>
struct zero_str {};
template <unsigned N, char... chars>
struct seq_gen { using type = typename seq_gen<N-1, '0', chars...>::type; };
template <char... chars>
struct seq_gen<0, chars...> { using type = zero_str<chars...>; };
template <size_t N>
struct zero_gen { using type = typename seq_gen<N-1, '0', '\0'>::type; };
template <>
struct zero_gen<0> { using type = zero_str<'\0'>; };
template<size_t N> using strsize = typename zero_gen<N>::type;
template<typename T, char... chars>
const char* n2hexHelper(T val, zero_str<chars...>)
{
thread_local static char hexstr[] = {'0', 'x', chars...};
/* convert to hex */
return hexstr;
};
template<typename T>
const char* n2hex(T val)
{
return n2hexHelper<T> (val, strsize<sizeof(T)*2>() );
}
int main()
{
std::cout << n2hex(1) << std::endl;
return EXIT_SUCCESS;
}
相反,我不希望将虚拟变量传递给辅助函数,并且能够执行以下操作:
template<typename T, char... chars>
const char* n2HexIdeal(T val)
{
thread_local static char hexstr[] = {'0', 'x', chars...}; //how to get chars... ?
/* convert to hex */
return hexstr;
}
我有两个主要问题。 1)参数包扩展是否可能像我的理想情况一样?或者是强制编译器推断出我的字符的唯一方法......是将它用作函数参数? 2)我对模板元编程不是很熟悉,所以我想知道我的上述解决方案是否存在任何明显的错误或惯用错误。
【问题讨论】:
标签: c++ c++11 variadic-templates template-meta-programming