Updating old idioms

New versions of C++ frequently introduce new idioms to replace older ones. Here are a few examples of how you can use Bronto to keep your codebase clean and modern.

Changing std::set to use contains()

In C++20, std::set added a contains method to replace the clunky find(...) != end() idiom. Here's how you can use Bronto to update your entire code base:

Write the following rule.

struct UpdateFindToContains : bronto::rewrite_expr {    
    template <typename Key>
    BRONTO_BEFORE()
    bool before(std::set<Key> s, Key k) { return s.find(k) != s.end(); }

    template <typename Key>
    BRONTO_AFTER()
    bool after(std::set<Key> s, Key k) { return s.contains(k); }
};

Sit back while Bronto modernizes your codebase.

Once all the existing uses have been updated, you could remove the rule above, but you can also leave it in so that any new code using the old idiom will automatically be updated as well!

See it in action on Compiler Explorer.

Switching to std::ranges for algorithms

In C++20, std::ranges added new functions for operating directly on containers instead of iterators. Here's how you can use Bronto to update your entire code base:

Write the following rule.

struct UpdateFindIf : bronto::rewrite_expr {
    BRONTO_BEFORE()
    auto before(auto c, auto pred) {
        return std::find_if(c.begin(), c.end(), pred);
    }

    BRONTO_AFTER()
    auto after(auto c, auto pred) {
        return std::ranges::find_if(c, pred);
    }
};

Sit back while Bronto modernizes your codebase.

Once all the existing uses have been updated, you could remove the rule above, but you can also leave it in so that any new code using the old idiom will automatically be updated as well!

See it in action on Compiler Explorer.