isocpp / isocpp/CppCoreGuidelines
T.70 Prefer if constexpr to function template overloading
Nobody has claimed this yet.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the proposed T.70 rule, its good and bad min examples, and the linked F.3 guidance. The issue does not name a file or test; completion would require agreeing on the rule wording, examples, and enforcement guidance.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- documentation
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100