How to convert an integer to a char array at compile time?

Hi,

I have the following code that attempts to convert an integer to a char array at compile time but for some reason it fails. It works fine at runtime though. The strange thing is that I am using constexpr everywhere and the location of the char array where to deposit the int value is a constexpr as well.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
template<int i, char* buffer, int N>
struct SetDigit
{
	constexpr static void doIt()
	{
		int digit = i % 10;
		buffer[N] = digit + '0';
		SetDigit<i / 10, buffer, N-1>::doIt();
	}
};

template<char* buffer, int N>
struct SetDigit<0,buffer, N>
{
	constexpr static void doIt()
	{
		buffer[N]= ' ';
		SetDigit<0, buffer, N-1>::doIt();
	}
};

template<char* buffer>
struct SetDigit<0, buffer, 0>
{
	constexpr static void doIt()
	{
		buffer[0] = ' ';
	}
};


struct IntToStr
{
	constexpr static std::size_t MAX = 10;
	static inline char buffer[MAX];

	template<int i>
	constexpr static char* Convert()
	{
		buffer[MAX - 1] = 0;
		SetDigit<i, buffer, MAX - 2>::doIt();
		return buffer;
	}
};


Using it like so gives an error:

1
2
3
4
5
void main()
{
	IntToStr::Convert<17>();
	static_assert(false, IntToStr::buffer);
}


This gives the following error:


expected a string literal
syntax error: identifier 'buffer' 


This is using Visual Studio 17 version 15.6.2..
Also, IntToStr is not accepted... why?

Regards,
Juan Dent

static_assert expects a string literal so I don't think you can use anything else.
ok, is there another way to display a compile time integral constant during compilation?
Use snprintf() and be sure allocate the proper amount of space to hold numbers up to 2^(sizeof(int)*CHAR_BIT). On a 64-bit machine, that will be 20 digit characters, plus 1 for the NULL terminator.

#include <stdio.h>
#define MAX_DIGITS 20

int n = 2007;
char str[MAX_DIGITS+1];
snprintf(str, MAX_DIGITS+1, "%d", n);

http://www.cetpainfotech.com/technology/c-language-training
Topic archived. No new replies allowed.