是否可以在编译时生成一个字符串?

时间:2014-07-04 04:04:19

标签: c++ templates c++11 string-formatting compile-time

在以下示例中,我在模板函数中使用snprintf来创建包含模板参数N的值的字符串。我想知道是否有一种方法可以在编译时生成这个字符串。

template <unsigned N>
void test()
{
    char str[8];
    snprintf(str, 8, "{%d}", N);
}

1 个答案:

答案 0 :(得分:4)

经过一番挖掘后,我在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;
}
还建议

boost::mpl,但此代码似乎更简单。

相关问题