Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates in C++, Generics in Java and the >> bit shift operator

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?

like image 863
noMAD Avatar asked Jan 21 '26 14:01

noMAD


2 Answers

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.

like image 165
Baltasarq Avatar answered Jan 23 '26 03:01

Baltasarq


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;
like image 27
Dietmar Kühl Avatar answered Jan 23 '26 02:01

Dietmar Kühl