简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM