如果我采用右移运算符的地址并将其作为模板参数传递,则右移符号会被误读为模板参数列表的末尾,由此产生的混淆会导致多个错误。
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;
}
添加括号的“技巧”在很多情况下都适用,其中表达式有歧义或被编译器误解。
关于c++ - 将右移运算符用作模板参数时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30828536/