My actual question is as follows:
In C++ nested parameters are required to have a space in between, like List< List<String> >. This is done such that the compiler can differentiate between the above and a bit shift >>. But the same thing is not true for Java List<List<String>> is perfectly valid. How does the JVM differentiate between the above and >> bit shift?
The difference is in the context that surrounds the supposed >> operator. When it is an operator, an expression is expected for both operands:
EXPR >> EXPR
An expression can be a variable, a literal, a function invokation, or a complex combination of all those elements. While in the case of a list declaration, however, there are no expressions involved, just types and id's. For example:
List<List<string >> id;
Actually, in the new standard the C++ compiler is able to make the difference as well.
The immediate issue in C++ is that template argument may actually include expressions: constant expressions are perfectly valid template arguments. I don't think this is true in Java. Here is an example where the expression would mess things up:
std::list<std::bitset<32 >> 2> > list_of_bitset8s;
That said, the original rule was imposed essentially to retain existing C++ parsers which tended to use relatively simple lexical analysis which was essentially build on top of context free regular expressions. Also, when templates were added nobody really anticipated that nested templates would be used a lot. As it turns out they are and C++2011 fixed the issue by allowing the use of closing angle brackets without intervening spaces legal. To disambiguate the rare cases where an expression using the right shift operator is used as template paramete parenthesis have to be used, i.e. the above declaration is legal with C++2003 and is illegal with C++2011. It has to be replaced by
std::list<std::bitset<(32 >> 2)>> list_of_bitset8s;
(well, the closing angle brackets may continue to use spaces if desired).
Of course, this is an incomplete fix because the following is still illegal:
::std::list<::std::bitset<8>> list of bitset8s;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With