将右移运算符用作模板参数时出现语法错误

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

如果我采用右移运算符的地址并将其作为模板参数传递,则右移符号会被误读为模板参数列表的末尾,由此产生的混淆会导致多个错误。

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; 
}

运行 Microsoft Visual Studio Express 2013 for Windows Desktop 版本 12.0.31101.00 更新 4 出现以下错误:

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

据我所知,operator>> > 符号被分解,所以它读作 operator>,然后是终止符 > 以关闭模板参数,并且以 lulz 的备用 > 结尾。我认为这是一个错误。

有什么方法可以改写它以使其被识别为有效吗?

简单地在 &TestStruct::operator>> 周围添加括号将强制 MSVC 正确解析它。

这段代码编译 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; 
}

添加圆括号的 "trick" 在许多情况下都有效,其中表达式有歧义或被编译器误解。