Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are all the syntax problems introduced by the usage of angle brackets in C++ templates?

In C++ templates are instantiated with angle brackets vector<int> and the Java and C# languages have adopted the same syntax for their generics.

The creators of D, however, have been quite vocal about the problems that angle brackets bring and they made a new syntax foo!(int) — but I've never seen too many details about what problems angle brackets bring, exactly.

One of them was when instantiating a template with another template vector<vector<int>>, which would cause some (older?) compilers to confuse the trailing '>>` with the bit-shift or streaming operators. The solution was to insert a space between the two angle brackets, but haven't compilers become able to parse that syntax, nowadays?

Another problem was when using the greater-than operator foo<3 > 2>. The parser would think that the operator actually closes the template instantiation; the fix was to introduce parentheses foo<(3 > 2)>. But I don't think there that many cases where you need to do this and, at any rate, I'd rather have to type the extra parentheses when they are needed, instead of introducing new syntax and always having to type the exclamation mark.

What other problems are there with angle brackets that made the D developers create a new syntax?

like image 707
Paul Manta Avatar asked Sep 05 '11 06:09

Paul Manta


People also ask

What are angle brackets used for in coding?

Angle brackets are commonly used to enclose a code of some type. For example, HTML tags and PageMaker tags are enclosed in angle brackets. They are also used on chat channels and in chat rooms to frame a comment or expression, such as <groan!> or <g>, which is short for <grin>.

What is angle bracket in C?

When you use angle brackets, the compiler searches for the file in the include path list. Angular brackets are used for standard inclusions.


1 Answers

Personally, the most hideous problem I have seen is the invocation of template functions in dependent context:

template <typename T> void foo(T t) {   t.bar<3>(); } 

This looks admittedly simple, but in fact is incorrect. The C++ Standard requires the introduction of the template keyword to disambiguate t.bar < 3 vs a method invocation yielding:

t.template bar<3>(); // iirk 

litb made some very interesting posts regarding the possible interpretation a compiler could come up with.

Regarding the >> issue, it's fixed in C++0x, but requires more clever compilers.

like image 77
Matthieu M. Avatar answered Oct 05 '22 22:10

Matthieu M.