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

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

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

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

最佳答案

经过更多的挖掘之后,我在 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 也有人建议,但这段代码似乎更简单。

关于c++ - 是否可以在编译时生成一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566547/

相关文章:

c++ - 定点幂函数

c++ - 是否可以将 bitset<8> 的值复制到一串数组而不进行转换?

c++检查范围内值的通用方法

c++ - 对于类模板定义中由 this-> 限定的类/命名空间名称,是否应该延迟名称查找?

C++ 重载运算符 < 带有 int 参数(与不保证为 int 的类型相比)

C++11 无锁栈

c++ - 如何展开模板特化

c++ - 排列列

c++ - 使用 getter 设置私有(private)变量

c++ - Lambda 捕获和内存管理