1
#define EXTERNAL_API_VERSION 1.12.1
std::string version = boost::lexical_cast<std::string>(EXTERNAL_API_VERSION);

This code generates a compilation error:

error C2143: syntax error : missing ')' before 'constant'
error C2059: syntax error : ')'

Are there any simple alternatives for casting number in such format (more then one dot) to string?

Sanich
  • 1,739
  • 6
  • 25
  • 43
  • `1.12.1` isn't a valid literal constant. – PaperBirdMaster Oct 15 '13 at 14:04
  • It's not a valid lexeme in C++, so no it's not possible. The only way to have versions in code is as strings. – Some programmer dude Oct 15 '13 at 14:04
  • @PaperBirdMaster you are right, but i have to cast it to string :-) – Sanich Oct 15 '13 at 14:05
  • 2
    @Sanich Then why not make it a string to begin with? – Some programmer dude Oct 15 '13 at 14:06
  • What's wrong with `const char* EXTERNAL_API_VERSION = "1.12.1";`? – juanchopanza Oct 15 '13 at 14:07
  • @JoachimPileborg The define {EXTERNAL_API_VERSION} is defined in external API. Can't touch that code. – Sanich Oct 15 '13 at 14:09
  • @juanchopanza and what's wrong with `const std::string EXTERNAL_API_VERSION("1.12.1");` ;) – PaperBirdMaster Oct 15 '13 at 14:11
  • Whose idea was it to define `EXTERNAL_API_VERSION` that way? This question seems to be the only Google hit for that identifier. BTW, I believe it's a valid token sequence: a floating-point constant `1.12`, followed by `.`, followed by an integer constant `1`. That sequence can't appear after preprocessing in a syntactically valid program, though ([you can't overload `.`](http://stackoverflow.com/q/520035/827263)), so that doesn't do you much good. – Keith Thompson Oct 22 '13 at 23:25

1 Answers1

5

Without touching EXTERNAL_API_VERSION, you need to expand that marco in two levels to a string literal:

#define S(X) #X
#define STR(X) S(X)

std::string version = STR(EXTERNAL_API_VERSION);
masoud
  • 55,379
  • 16
  • 141
  • 208
  • 1
    @Sanich: In first step you expand `EXTERNAL_API_VERSION` to `1.12.1`, in the next step you make it a string literal by `#`, `"1.12.1"`. You can not mix these two step in one. It's useful to read [this](http://stackoverflow.com/a/19343239/952747) – masoud Oct 16 '13 at 11:25