相关疑难解决方法(0)

C++在编译时将整数转换为字符串

我想做这样的事情:

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库可能允许这样但我无法弄清楚如何使用它来实现这一点.这可能吗?

c++ string templates boost boost-mpl

17
推荐指数
4
解决办法
8441
查看次数

使用constexpr将数字转换为字符串文字

我正在寻找一种在编译时将数字转换为字符串文字的方法.它应该看起来像这样:

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而不是宏来帮助泛型编程.

c++ c++11

9
推荐指数
1
解决办法
4905
查看次数

标签 统计

c++ ×2

boost ×1

boost-mpl ×1

c++11 ×1

string ×1

templates ×1