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

标签 c++ string templates boost boost-mpl

我想做这样的事情:

template<int N>
char* foo() {
  // return a compile-time string containing N, equivalent to doing
  // ostringstream ostr; 
  // ostr << N;
  // return ostr.str().c_str();
}

似乎 boost MPL 库可能允许这样做,但我真的不知道如何使用它来实现这一点。这可能吗?

最佳答案

首先,如果您通常在运行时知道数字,则可以轻松构建相同的字符串。也就是说,如果你的程序中有12,你也可以有"12"

预处理器宏还可以为参数添加引号,因此您可以编写:

#define STRINGIFICATOR(X) #X

这样,每当你写STRINGIFICATOR(2),它都会产生“2”。

然而,它实际上可以在没有宏的情况下完成(使用编译时元编程)。这并不简单,所以我不能给出确切的代码,但我可以给你一些想法:

  1. 使用要转换的数字编写递归模板。模板会递归到base case,即数量小于10。
  2. 在每次迭代中,您可以将 N%10 位数字转换为 T.E.D. 字符。建议,and 使用 mpl::string 来构建附加该字符的编译时字符串。
  3. 你最终会构建一个 mpl::string,它有一个静态 value() 字符串。

我花时间将其作为个人练习来实现。最后还不错:

#include <iostream>
#include <boost/mpl/string.hpp>

using namespace boost;

// Recursive case
template <bool b, unsigned N>
struct int_to_string2
{
        typedef typename mpl::push_back<
                typename int_to_string2< N < 10, N/10>::type
                                         , mpl::char_<'0' + N%10>
                                         >::type type;
};

// Base case
template <>
struct int_to_string2<true,0>
{
        typedef mpl::string<> type;
};


template <unsigned N>
struct int_to_string
{
        typedef typename mpl::c_str<typename int_to_string2< N < 10 , N>::type>::type type;
};

int
main (void)
{
        std::cout << int_to_string<1099>::type::value << std::endl;
        return 0;
}

关于C++ 在编译时将整数转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6713420/

相关文章:

templates - umbraco模板错误: "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

python - 如何将 vtkSphere 保存到 VTK 文件?

c++ - 陷入无限循环? (可能是)

c++ - 如何找到文本文档中最长的单词?

检查传递的字符串是否为整数

从 char16_t* 复制到 char16_t*

java - 有什么方法可以将字符串数组转换为字符数组吗?

javascript - 为什么这个跨度在文本上方?我想要它在文字旁边

c++ - WideCharToMultiByte 问题

c++ - 将结构作为模板参数传递 - 如何修复此代码?