C++ Logo


Advanced search

Subject: [std-proposals] Language Feature for Reducing Duplicated Code
From: David Ledger (DavidLedger_at_[hidden])
Date: 2020-07-18 00:29:17

Hello Everyone,

Duplicate function bodies seem to exist everywhere in C++ codebases.
This attempts to reduce duplicate code by allowing deduction of const for a function. Allowing a const and non-const function to have the same function body but call the appropriate const or non-const functions.

What I'm talking about it that everyone writes:

        iterator begin();
        iterator begin() const;

        T & operator[](size_t i);
        T const & operator[](size_t i) const;

Same for operator[] and function at, and begin, end, front, back etc...

For the const and non-const versions of the function, often the body of these functions is identical, all that changes is the return type and the selected overloads in the function body. I don't really see the benefit for this and want to improve this.

So I want to propose the following:

        const(boolean expr)
        noexcept(auto), we already have noexcept(boolean expr)

This would let me write:

        iterator begin() const(auto);

The problem this introduces is how is the return type determined here, well to do that we would need the bool available for the user:

        abbreviated syntax:
        auto begin() const(is_const) -> iterator<is_const>;


        template syntax:
        template <bool is_const>
        auto begin() const(is_const) -> iterator<is_const>;

        template syntax with return using conditional_t
        auto begin() const(is_const) -> conditional_t<is_const, citerator, iterator>;

There are additional benefits here:
- Keep function logic in one place, not many.
- Use template parameters of a class to fully const or not-const all functions in a class.
- Reduce the maintenance cost of std library code by halving (in some cases) the number of overloads.

As I see it, what needs to be solved:
- Member function pointers, how to get an exact one?

I'm happy to write up a proposal for this to submit.
Anyone have and feedback before I write it up?

     David Ledger

STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups