C ++在编译时转换为字符串整数 [英] C++ convert integer to string at compile time

查看:137
本文介绍了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();
}

这似乎是助推MPL库可能允许这一点,但我无法真正弄清楚如何使用它来实现这一目标。这可能吗?

It seems like the boost MPL library might allow this but I couldn't really figure out how to use it to accomplish this. Is this possible?

推荐答案

首先,如果平时你在运行时知道电话号码,您可以轻松地构建相同的字符串。也就是说,如果你有 12 在你的程序中,可以有也12

First of all, if usually you know the number at run time, you can as easily build the same string. That is, if you have 12 in your program, you can have also "12".

preprocessor宏还可以添加引号为参数,所以你可以写:

Preprocessor macros can add also quotes to arguments, so you can write:

#define STRINGIFICATOR(X) #X

此,当你写 STRINGIFICATOR(2),就会产生2。

This, whenever you write STRINGIFICATOR(2), it will produce "2".

然而,它实际上的可以的无宏来完成(使用编译时元编程)。它不是简单的,所以我不能给出确切code,但我可以给你如何做到这一点的想法:

However, it actually can be done without macros (using compile-time metaprogramming). It is not straightforward, so I cannot give the exact code, but I can give you ideas on how to do it:


  1. 编写使用要转换的数递归模板。该模板将递归直至碱的情况下,即,数小于10。

  2. 在每次迭代中,可以有N个%的10位被转换成一个字符作为T.E.D.顾名思义,的使用 MPL ::字符串来构建追加该字符的编译时间字符串。

  3. 您最终会建立一个 MPL ::字符串,具有静态值()字符串。

  1. Write a recursive template using the number to be converted. The template will recurse till the base case, that is, the number is less than 10.
  2. In each iteration, you can have the N%10 digit to be converted into a character as T.E.D. suggests, and using mpl::string to build the compile-time string that appends that character.
  3. You'll end up building a mpl::string, that has a static value() string.

我接过来实现它作为个人锻炼的时间。不坏的结尾:

I took the time to implement it as a personal exercise. Not bad at the end:

#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 ++在编译时转换为字符串整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆