r/cpp • • Jul 20 '26

C++26: what is “template for”? Learning with simple example.

https://techfortalk.co.uk/2026/07/20/c26-what-is-template-for/

I have been exploring C++26 in bits and bobs and this one is about template for - a c++26 feature which I find useful. This is a short article explaining how to use this feature with the help of a simple example.

75 Upvotes

43 comments sorted by

View all comments

Show parent comment

2

u/_Noreturn Jul 22 '26 edited Jul 22 '26

because there is no else if in the C++ grammar as a single construct

This is C++ grammar for if statement

statement: buncha things
                  | if-statement
if-statement:
    if [constexpr] ( condition ) statement [else statement]

[] means optional.

as you can see else mentions "statement" and "statement" mentions "if-statement" this is recursion when you do


if (c1)
else if(c2)
else 
// is just this

if (c1) {
       ;
} else {
    if (c2)   {
        ;
    } else {
        ;
    }
}

so if you wanted "constexpr else if" you would need to create a new grammar thing for it to work but with "if" it just works naturally due to recursion.

if you allowed "constexpr" before else as a speciality then it would allow "constexpr else if constexpr" which is mirrored but awkward

2

u/fdwr fdwr@github 🔍 Jul 22 '26 edited Jul 23 '26

because there is no else if in the C++ grammar as a single construct

Hehe, even after 20+ years of C++, I still sometimes use the preprocessor for a few things (typing #if, #elif...) and then right afterward try typing elif outside the preprocessor context, only to get a build error. Oh yeah, that odd inconsistency arises again 😉.

2

u/_Noreturn Jul 22 '26

ngl I don't know why they didn't do #else if in the preprocessor I guess it is to not support multi token keywords in the preprocessor.

It is awkward since I do sometimes type #else if only to get some weird error about ignoring whitespace

2

u/fdwr fdwr@github 🔍 Jul 23 '26

Indeed, I'd be okay with either #elif and elif, or #else if and else if, but mixing the two is 😵‍💫.