Chr*_*s_F 3 c++ templates string-formatting compile-time c++11
在下面的示例中,我snprintf在模板函数内部使用来创建包含模板参数值的字符串N。我想知道是否有办法在编译时生成这个字符串。
template <unsigned N>
void test()
{
char str[8];
snprintf(str, 8, "{%d}", N);
}
Run Code Online (Sandbox Code Playgroud)
经过一番挖掘后,我在 SO 上发现了这个: https: //stackoverflow.com/a/24000041/897778
适合我的用例我得到:
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;
}
Run Code Online (Sandbox Code Playgroud)
boost::mpl也有人建议,但这段代码似乎更简单。