使用 Visual C++ 2013,以下代码会产生一个奇怪的编译错误:
/// header.h
class Test
{
public:
template <typename Func>
void operator[](Func f)
{
f();
}
};
template <typename T>
void funct()
{
Test t;
t[[](){; }]; // line 16 // The same error with t[ ([](){; }) ];
}
/// main.cpp
int main()
{
funct<int>();
// funct();
}
错误:
1>c:\path\to\header.h(16): error C2958: the left bracket '[' found at 'e:\path\to\header.h(16)' was not matched correctly
1>c:\path\to\header.h(16): error C2059: syntax error : ']'
1>c:\path\to\header.h(17): error C2059: syntax error : '}'
1>c:\path\to\header.h(17): error C2143: syntax error : missing ';' before '}'
当 lambda 函数体没有任何语句时,不会发生此错误:
template <typename T>
void funct()
{
Test t;
t[[](){ }]; // line 16 // No semicolon - No statement - No errors
}
或者当函数不是模板时:
// Ordinary function - No errors
void funct()
{
Test t;
t[[](){; }]; // line 16
}
我想我在这个编译器中发现了一个错误。但是,如果有人知道一种没有错误且不使用变量来保存 lambda 函数的方法,那就太好了。