C++ syntax rant (template guides)

C++ syntax is notoriously complex and full of gotchas both for compilers and for humans. I don’t know what was the reasoning in selecting the syntax for template deduction guides (C++ 17),  but it is outright confusing, in my humble opinion. Check it out:

// this is a deduction guide
template <std::integral T>
MyClass(T) -> MyClass<IntTag, T>;

// this is a function declaration
template<class T>
auto myClass(T) -> MyClass<IntTag,T>;

I mean, what was wrong with having something like template guide <std::integral T>? Yes, you would need a new (contextual) keyword, but at least it would be readable. I am sure the standard committee had very deep sounding reasons to choose the syntax they chose, but the result is not very readable to be honest.


I asked this question during a great talk about deduction guides given by Nina Ranns at CppCon 2023. The similarity between the function declaration syntax and deduction guide syntax is not coincidental. Internally, class template argument deduction is based on function template argument deduction, it builds a set of “notional functions” from the class constructor signatures, and deduction guides put additional “pseudo functions” into that set. This is my very rough understanding, which may not be entirely correct.

But these are implementation details, which did not have to leak into the syntax. According to Nina, alternative syntaxes were not carefully considered, the focus was on getting the guides to work.

This is understandable, but in the great scheme of things it added yet another element of confusion into already complicated C++ syntax where it is not always clear what is what. I believe we would be better off if template deduction guides had a clear indicator like template guide <std::integral T>...

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *