Say I have
constexpr const std::uint8_t major = 1;
constexpr const std::uint8_t minor = 10;
constexpr const std::uint8_t bugfix = 0;
and I want
constexpr const char* version_string(){ ... }
to return the equivalent of "1.10.0"
in this example, how would I do it?
I assume I'll need both of these, in constexpr
:
- integer to string conversion
- string concatenation
The problem is purely academic, and I see little to no use to actually have it constexpr
other than "it's possible". I just can't see how this would pan out. I'm willing to accept C++1y solutions that work on GCC 4.9 and Clang 3.4/3.5.
I believe I have found nearly what I seek on some Japanese blogs:
I will see what I can do with these, and perhaps answer this self-declared interesting question myself when I'm satisfied with the result.
Here is a C++11 solution. It uses class templates with
char...
parameter pack to simulate strings:See live example.
Here is my quick and dirty solution: http://coliru.stacked-crooked.com/a/43c9b365f6435991
It exploits the fact that a 'major.minor.fix' string will be quite short, so I just use a fixed-size array big enough to hold the string. The int-to-string function uses
push_front
to prepend characters to string, so the whole string grows from end of buffer.Update:
It's probably better to make a dedicated class for version string generation, and put all the functions in it: http://coliru.stacked-crooked.com/a/5e5ee49121cf6205
Here's a little C++1y solution --- I think I LOVE C++1y.
Now the
constexpr itoa
:We can then simplify the usage:
And a usage example:
Live example @ coliru's clang++3.4