I have a vector of 2N lines where the second half (N lines) is basically the same as the first half but with a single character changed, e.g.:
std::vector<std::string> tests{
// First half of lines with '=' as separator between key and value
"key=value",
...
// Second half of lines with ' ' as separator between key and value
"key value",
...
};
Is there a way to parameterize the separator (i.e., = or ) to avoid repeating the lines during the initialization, using the uniform initialization construct? I wonder if there's a better way than creating it with a for loop.
By reading from documentation, it seems not to be possible.
Thanks
Since this is tagged c++17 and you said the strings are known at compile-time, it is technically possible to perform uniform initialization by leveraging a variadic function-template and unpacking the parameters twice, and this would produce the modified string at compile-time.
The idea, in the simplest form, is to do this:
Where
to_space_stringis a class that returns a string-like object, done at compile-time.To do this, we need to make a simple holder that acts like a string is convertible to
std::string_viewat compile time. This is to ensure that the string we modify has its own separate lifetime and does not dangle:Then all we need is the function that takes a compile-time string (array of
chars), copies it into thestatic_string<N>object, and returns it:The last needed tweak would be for the initializer list to be a sequence of
std::stringobjects, which we can do withstatic_casts:With this, code like:
will produce a vector containing
hello=worldgoodbye=worldhello worldgoodbye worldLive Example
Note:
If we didn't use a
static_stringor some equivalent and instead usedstring_viewdirectly, the string would dangle. For example:In the above case, we return a reference to temporary storage
storage[N], thus causing a dangling pointer (UB). Thestatic_stringcreates an object first whose lifetime is passed into the caller (make_string_vector) and then gets converted to astd::string.