What are use cases for structured bindings?

前端 未结 4 1384
滥情空心
滥情空心 2020-12-05 13:24

C++17 standard introduces a new structured bindings feature, which was initially proposed in 2015 and whose syntactic appearance was widely discussed later.

Some use

4条回答
  •  有刺的猬
    2020-12-05 14:18

    Barring evidence to the contrary, I think Structured Bindings are merely a vehicle to deal with legacy API. IMHO, the APIs which require SB should have been fixed instead.

    So, instead of

    auto p = map.equal_range(k);
    for (auto it = p.first; it != p.second; ++it)
        doSomethingWith(it->first, it->second);
    

    we should be able to write

    for (auto &e : map.equal_range(k))
        doSomethingWith(e.key, e.value);
    

    Instead of

    auto r = map.insert({k, v});
    if (!r.second)
        *r.first = v;
    

    we should be able to write

    auto r = map.insert({k, v});
    if (!r)
        r = v;
    

    etc.

    Sure, someone will find a clever use at some point, but to me, after a year of knowing about them, they are still an unsolved mystery. Esp. since the paper is co-authored by Bjarne, who's not usually known for introducing features that have such a narrow applicability.

提交回复
热议问题