2

使用 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 函数的方法,那就太好了。

4

1 回答 1

5

VC++ 正确地拒绝了这个代码,但出于错误的原因——这是一个错误。根据 [dcl.attr.grammar]/6,它的格式不正确:

只有在引入属性说明符时才会出现两个连续的左方括号标记。[注意: 如果两个连续的左方括号出现在不允许使用属性说明符的地方,即使括号匹配替代的语法产生,程序也是格式错误的。 — 尾注] [示例:

int p[10];
void f() {
    int x = 42, y[5];
    int(p[[x] { return x; }()]); // error: invalid attribute on a nested
                                 // declarator-id and not a 
                                 // function-style cast of an element of p.

    y[[] { return 2; }()] = 2; // error even though attributes are not allowed
                               // in this context.
}

—结束示例]

因此,请尝试将 lambda 表达式括在两个括号中,如下所示。

t[ ([](){; }) ];

或者写

auto&& closure = [](){; };
t[closure]; // move here if correct value category is desired
于 2014-12-14T11:07:26.643 回答