我想做这样的事情:
template<int N>
char* foo() {
// return a compile-time string containing N, equivalent to doing
// ostringstream ostr;
// ostr << N;
// return ostr.str().c_str();
}
Run Code Online (Sandbox Code Playgroud)
似乎boost MPL库可能允许这样但我无法弄清楚如何使用它来实现这一点.这可能吗?
我正在寻找一种在编译时将数字转换为字符串文字的方法.它应该看起来像这样:
template <unsigned num>
struct num_to_string {
constexpr static char value[] = /* ... magic goes here ... */;
};
Run Code Online (Sandbox Code Playgroud)
所以这num_to_string<5>::value等于"5"或{'5', '\0'}.
这对于在编译时从一些其他constexpr数计算结果的数字生成字符串非常有用.
另请注意,我只对unsigned数字感兴趣,因为这应该更容易处理.签名版本的奖励积分:)
编辑:请注意,这类似于C++在编译时将整数转换为字符串,但不一样.在这里,我明确地想要使用constexpr而不是宏来帮助泛型编程.