gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:07:11 26 4
gpt4 key购买 nike

我想做这样的事情:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com