我想做类似于这样的事情:
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"。
然而,实际上可以使用编译时元编程(compile-time metaprogramming)来完成,而无需使用宏定义。这并不是直接的操作,因此我无法给出确切的代码,但我可以给您一些实现思路:
mpl::string
来构建编译时字符串,以附加该字符。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;
}
mpl
提供了类型 push_front<string_type, char>::type
,用于定义一个在现有字符串前添加字符的编译时字符串。 - Diego Sevilla我知道这个问题现在已经有几年了,但是我想要一个使用纯C++11的解决方案,没有boost依赖。因此,这里提供一些代码(灵感来自于另一个问题的答案):
```cpp // code goes here ```/* IMPLEMENTATION */
/* calculate absolute value */
constexpr int abs_val (int x)
{ return x < 0 ? -x : x; }
/* calculate number of digits needed, including minus sign */
constexpr int num_digits (int x)
{ return x < 0 ? 1 + num_digits (-x) : x < 10 ? 1 : 1 + num_digits (x / 10); }
/* metaprogramming string type: each different string is a unique type */
template<char... args>
struct metastring {
const char data[sizeof... (args)] = {args...};
};
/* recursive number-printing template, general case (for three or more digits) */
template<int size, int x, char... args>
struct numeric_builder {
typedef typename numeric_builder<size - 1, x / 10, '0' + abs_val (x) % 10, args...>::type type;
};
/* special case for two digits; minus sign is handled here */
template<int x, char... args>
struct numeric_builder<2, x, args...> {
typedef metastring<x < 0 ? '-' : '0' + x / 10, '0' + abs_val (x) % 10, args...> type;
};
/* special case for one digit (positive numbers only) */
template<int x, char... args>
struct numeric_builder<1, x, args...> {
typedef metastring<'0' + x, args...> type;
};
/* convenience wrapper for numeric_builder */
template<int x>
class numeric_string
{
private:
/* generate a unique string type representing this number */
typedef typename numeric_builder<num_digits (x), x, '\0'>::type type;
/* declare a static string of that type (instantiated later at file scope) */
static constexpr type value {};
public:
/* returns a pointer to the instantiated string */
static constexpr const char * get ()
{ return value.data; }
};
/* instantiate numeric_string::value as needed for different numbers */
template<int x>
constexpr typename numeric_string<x>::type numeric_string<x>::value;
/* SAMPLE USAGE */
#include <stdio.h>
/* exponentiate a number, just for fun */
static constexpr int exponent (int x, int e)
{ return e ? x * exponent (x, e - 1) : 1; }
/* test a few sample numbers */
static constexpr const char * five = numeric_string<5>::get ();
static constexpr const char * one_ten = numeric_string<110>::get ();
static constexpr const char * minus_thirty = numeric_string<-30>::get ();
/* works for any constant integer, including constexpr calculations */
static constexpr const char * eight_cubed = numeric_string<exponent (8, 3)>::get ();
int main (void)
{
printf ("five = %s\n", five);
printf ("one ten = %s\n", one_ten);
printf ("minus thirty = %s\n", minus_thirty);
printf ("eight cubed = %s\n", eight_cubed);
return 0;
}
输出:
five = 5
one ten = 110
minus thirty = -30
eight cubed = 512
使用C++14即可实现此功能,无需外部依赖。标准的关键扩充是具有非平凡constexpr
构造函数的能力,使得该功能可以包含在一个简单的类中。
给定一个整数模板参数,构造函数可以执行整数到字符串的转换。这被存储在一个成员字符缓冲区中,其大小由另一个constexpr
函数确定。然后,一个用户定义的转换函数提供对缓冲区的访问:
#include <cstdint>
template<std::intmax_t N>
class to_string_t {
constexpr static auto buflen() noexcept {
unsigned int len = N > 0 ? 1 : 2;
for (auto n = N; n; len++, n /= 10);
return len;
}
char buf[buflen()] = {};
public:
constexpr to_string_t() noexcept {
auto ptr = buf + buflen();
*--ptr = '\0';
if (N != 0) {
for (auto n = N; n; n /= 10)
*--ptr = "0123456789"[(N < 0 ? -1 : 1) * (n % 10)];
if (N < 0)
*--ptr = '-';
} else {
buf[0] = '0';
}
}
constexpr operator const char *() const { return buf; }
};
最后,一个变量模板(另一个C++14的新增功能)简化了语法:
template<std::intmax_t N>
constexpr to_string_t<N> to_string;
puts(to_string<62017>); // prints "62017"
该功能可以扩展以支持其他进制(例如十六进制),宽字符类型和常见的容器接口;我将所有内容打包到一个头文件中,并在GitHub上发布,网址是:tcsullivan/constexpr-to-string。
使用C++20,这也可以扩展以支持浮点数。需要一个容器类型来处理浮点字面量,而此前它不能作为模板参数。请查看GitHub存储库中的f_to_string.hpp
头文件以获取实现。
constexpr
允许的扩展)。最好至少在答案本身中展示一个最简版本。 - Peter Cordes #define NUM(x) #x
很遗憾,这不适用于非类型模板参数。
NUM(1+1)
会得到"1+1"
的结果。 - hammar#define _NUM(x) #x
后跟 #define NUM(x) _NUM(x)
。 - vanzaNUM(foo);
,其中 enum { foo = 42 };
。宏将产生 "foo"
而不是 "42"
。 - greatwolf在一些情况下,如果你知道数字范围永远不会超出0..9
,则可以使用以下技巧:
return '0' + N;
一开始可能有点受限,但是我很惊讶这种情况有多少次出现。
哦,我知道这返回的是一个char
而不是std::string
。这是一个特性。string
不是内置语言类型,因此没有办法在编译时创建它。
char *
的要求。 - M.M另一个有用的选项:
template <int i, bool gTen>
struct UintToStrImpl
{
UintToStrImpl<i / 10, (i > 99)> c;
const char c0 = '0' + i % 10;
};
template <int i>
struct UintToStrImpl <i, false>
{
const char c0 = '0' + i;
};
template <int i, bool sign>
struct IntToStrImpl
{
UintToStrImpl<i, (i > 9)> num_;
};
template <int i>
struct IntToStrImpl <i, false>
{
const char sign = '-';
UintToStrImpl<-i, (-i > 9)> num_;
};
template <int i>
struct IntToStr
{
IntToStrImpl<i, (i >= 0)> num_;
const char end = '\0';
const char* str = (char*)this;
};
std::cout << IntToStr<-15450>().str;
std::string
是运行时的。你可以做半运行时的魔法,但不是纯编译时的。预处理器是你最好的选择。 - user405725itoa
函数只能在运行时使用。 - Thomas Matthews