This SO answer lists some shortcomings of C++17 decomposition declarations (the feature formerly known as "structured binding"). For example, you can't give explicit types to the new variables, and so on. But one big shortcoming I'm running into isn't mentioned there, so I wonder if there's a known workaround that I'm just not thinking of.
Consider this JSON-parsing code (which may contain other bugs; please ignore them for the purposes of this question):
using Value = std::any;
using String = std::string;
using Object = std::map<String, Value>;
std::pair<String, const char *> load_string(const char *p, const char *end);
std::pair<Value, const char *> load_value(const char *p, const char *end);
const char *skip_spaces(const char *p, const char *end);
std::pair<Object, const char *> load_object(const char *p, const char *end)
{
p = skip_spaces(p, end);
if (p == end || *p++ != '{') throw ParseError("Expected {");
p = skip_spaces(p, end);
Object result;
if (p == end && *p == '}') {
// the object has no key-value pairs at all
} else {
while (true) {
auto [key, p] = load_string(p, end);
p = skip_spaces(p, end);
if (p == end || *p++ != ':') throw ParseError("Expected :");
auto [value, p] = load_value(p, end);
result.insert_or_assign(std::move(key), std::move(value));
p = skip_spaces(p, end);
if (p == end) throw ParseError("Expected , or }");
if (*p == '}') break;
if (*p++ != ',') throw ParseError("Expected , or }");
}
}
return {result, p+1};
}
This would work great, except that the lines starting auto [key, p] =
and auto [value, p] =
are invalid! The variable p
has already been declared. I'm trying to assign p
a new value, but I don't want to create a whole new local variable.
I would prefer not to use std::tie(key, p) =
, because that requires me to give a declaration for key
before the assignment. This is the familiar old objection to std::tie
. Which I could have sworn was the reason structured binding was introduced into the language!
So is there any workaround — any nice clean way of writing the combination construct-key
-in-place-and-also-assign-to-p
that expresses my intention?
It's strange how I never missed this feature before, but as soon as you give me structured binding to play with, the first thing I try doesn't work. :(