Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax errors when right shift operator is used as a template parameter

If I take the address of a right shift operator and pass it as a template parameter, the right shift symbol is being misread as the end of the template parameter list, and the resulting confusion is causing multiple errors.

template <class T, void(T::*)(int)> struct TemplateMagic {};
struct TestStruct { void operator>> (int) {} };

int main() {
//All the errors are on this line:
    TemplateMagic<TestStruct, &TestStruct::operator>> >* ptr; 
}

Running this in Microsoft Visual Studio Express 2013 for Windows Desktop Version 12.0.31101.00 Update 4 gives the following errors:

error C2143 : syntax error : missing ';' before '>'

error C2275 : 'TestStruct' : illegal use of this type as an expression

error C2833 : 'operator >' is not a recognized operator or type

As far as I can tell, the operator>> > symbols are being broken apart so it reads it as operator>, followed by a terminating > to close the template arguments, and ending with a spare > for the lulz. I assume this is a bug.

Is there any way to reword this so it gets recognized as valid?

like image 770
Weak to Enuma Elish Avatar asked Oct 19 '22 09:10

Weak to Enuma Elish


1 Answers

Simply adding parentheses around &TestStruct::operator>> will force MSVC to parse it correctly.

This code compiles with MSVC 19.00.23008.0 :

template <class T, void(T::*)(int)> struct TemplateMagic {};
struct TestStruct { void operator>> (int) {} };

int main() {
    TemplateMagic<TestStruct, (&TestStruct::operator>>) >* ptr; 
}

The "trick" of adding parentheses will work in many situations where an expression is ambiguous or misunderstood by the compiler.

like image 174
tux3 Avatar answered Oct 29 '22 15:10

tux3