Skip to content

T.70 Prefer if constexpr to function template overloading #2099

Open
@Eisenwave

Description

@Eisenwave

Here is a suggestion for a rule which encourages the use of if constexpr.
Not only do we repeat ourselves and keep logic less fragmented, we also save on compile times typically, because overload resolution is very expensive.

I'm not so sure if the recursive min example demonstrates it best, perhaps someone else can think of a better one.

T.70 Prefer if constexpr to function template overloading for short functions

Reason
  • Overloading is complicated, and overload resolution is expensive.
  • We repeat ourselves less.
  • Logic is often simplified and in one place.
Example, good
template<typename Head, typename... Tail>
auto min(const Head& head, const Tail&... tail)
{
    // can't be regular if-statement because else-block
    // would fail to compile for empty Tail
    if constexpr (sizeof...(Tail) == 0) { return head; }
    else {
        auto m = min(tail...);
        return head < m ? head : m;
    }
}
Example, bad
template<typename T>
auto min(const T& x) { return x; }

// bad: we've repeated the name "min", and must keep all function definitions in sync
template<typename Head, typename... Tail>
auto min(const Head& head, const Tail&... tail)
{
    auto m = min(tail...);
    return head < m ? head : m;
}
Note

Long function templates are difficult to read and understand. Consider F.3: Keep functions short and simple

Enforcement

Flag short, overloaded function templates.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions