Daily C++ Tip 3

One function instead of const/non-const overload pairs (deducing this)

One explicit object parameter replaces the const and non-const overload pair.

An explicit object parameter lets one function see whether it was called on a const object, replacing the duplicated overload pair.

#include <iostream>
#include <type_traits>

struct Counter {
    int n = 0;
    // One function instead of const/non-const overload pairs.
    void bump(this auto&& self) {
        if constexpr (std::is_const_v<std::remove_reference_t<decltype(self)>>) {
            std::cout << "read-only: n=" << self.n << '\n';
        } else {
            ++self.n;
            std::cout << "bumped: n=" << self.n << '\n';
        }
    }
};

int main() {
    Counter c;
    c.bump();
    const Counter d;
    d.bump();
}

Observed output:

bumped: n=1
read-only: n=0

Facts verified 2026-11-04. The code on this page was compiled and run on the box with GCC 16.2.0 at -std=c++23 -Wall -Wextra; the outputs quoted are the observed outputs. MSVC was not tested.

Back to the daily tips index

Keep Exploring

Keep exploring the docs, samples, and free tools to continue your evaluation.