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 0 to nullptr
In C++11, the nullptr keyword was introduced, which provides a more expressive
and type-safe mechanism for writing a literal null pointer. Update from an old
idiom of using a literal 0 with the following:
Write the following rule.
struct RewriteZeroToNullptr : bronto::rewrite_expr {
template <typename T>
BRONTO_BEFORE()
T* before() { return 0; }
template <typename T>
BRONTO_AFTER()
T* after() { return nullptr; }
};Sit back while Bronto modernizes your codebase.
Optional: Add a macro rewrite rule to modernize usages
of NULL in the 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.
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.