Kla*_*aus 10 c++ lambda attributes language-lawyer c++11
在下标运算符中使用lambda似乎不适用于g ++和clang.
这是c ++标准中的实现错误还是"不快乐"规则?
例:
class A
{
public:
template<typename T> void operator[](T) {}
template<typename T> void operator()(T) {}
};
int main()
{
A a;
a[ [](){} ]; // did not compiler: see error message
a( [](){} ); // works as expected
}
Run Code Online (Sandbox Code Playgroud)
错误:
main.cpp:13:6: error: two consecutive '[' shall only introduce an attribute before '[' token
a[ [](){} ];
^
main.cpp:13:15: error: expected primary-expression before ']' token
a[ [](){} ];
Run Code Online (Sandbox Code Playgroud)
我知道属性以"[["开头,但我想知道"[["(带有一个或多个空格)也像:
void func( int x [ [gnu::unused] ] ) {} // compiles fine! :-(
Run Code Online (Sandbox Code Playgroud)
你必须将lambda括在括号中.否则,编译器将两个[[视为引入属性.
使用operator delete会出现类似的问题.例如,你必须写
delete ( [] { return ( new int() ); }() );
Run Code Online (Sandbox Code Playgroud)
要么
delete [] ( [] { return ( new int[10] ); }() );
Run Code Online (Sandbox Code Playgroud)
那就是你必须将lambda括在括号中.
[dcl.attr.grammar] 对此进行了介绍。连续两个[是一个属性,因此您必须用括号括起来或执行其他操作来明确您的意图:
\n\n仅当引入属性说明符或在属性参数子句的平衡令牌序列内时,才应出现两个连续的左方括号标记。[ 注意:如果在不允许属性说明符的地方出现两个连续的左方括号,则即使括号与替代语法产生式匹配,程序也是格式错误的。\xe2\x80\x94结束注] [ 示例:
\n\nRun Code Online (Sandbox Code Playgroud)\n\nint p[10];\nvoid f() {\n int x = 42, y[5];\n int(p[[x] { return x; }()]); // error: invalid attribute on a nested\n // declarator-id and not a function-style cast of\n // an element of p.\n y[[] { return 2; }()] = 2; // error even though attributes are not allowed\n // in this context.\n int i [[vendor::attr([[]])]]; // well-formed implementation-defined attribute.\n}\n\xe2\x80\x94结束示例]
\n