Reputation: 73
Is there a C++ way of concatenating two constexpr C-strings at compile time? I know how to do it in C with defines, but would really rather have the scope reduction and explicit type system of C++. My primary goal is to have a nice way of concatenating strings at compile time in one line.
Here's an example of what does work in the way I don't want:
#define STR1 "foo"
#define STR2 "blah"
#define CONCATED STR1 STR2
Here's an example of what doesn't work in the way I do want:
constexpr const char *str1 = "foo";
constexpr const char *str2 = "blah";
constexpr const char *concated = str1 str2;
Upvotes: 1
Views: 242
Reputation: 36597
It can only be done at compile time with string literals.
constexpr const char concatenated[] = "foo" "blah";
This is the effect achieved by your CONCATED
macro (in fact, it is literally how the preprocessor expands usage of that macro).
If you want to concatenate named variables, then it is not possible to satisfy your requirement(s) of doing concatenation at compile time avoiding use of heap or stack.
The two obvious choices are to allocate enough memory to hold the result and then use strcat()
, or to use the std::string
type. Both of these involve using heap or stack (depending on how you allocate memory, and how the allocator you choose for std::string
works) and both do the concatenation at run time.
Upvotes: 1