Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are lookup rules when calling function from lambda?

Tags:

c++

c++11

The following example demonstrates the problem I encountered in VC++ 2010:

class Foo
{
    template<class T>
    static T foo(T t) { return t; }

public:
    void test()
    {
        auto lambda = []() { return foo(1); }; // call to Foo::foo<int>
        lambda();
    }
};

VC++ produces: error C3861: 'foo': identifier not found

If I qualify the call to foo: Foo::foo(1); then this example compiles with a warning: warning C4573: the usage of 'Foo::foo' requires the compiler to capture 'this' but the current default capture mode does not allow it

What does the standard say about this case? Should unqualified name be found? Does the qualified name require capturing this?

like image 216
Gene Bushuyev Avatar asked Sep 02 '11 08:09

Gene Bushuyev


2 Answers

Microsoft has been seeing this problem reported in a number of cases. See:

Scope Resolution with lambdas interferes with namespace and type resolution

Template resolution in lambdas

As you've found out, explicit resolution allows it to find the name. There is an additional warning about this which is also a compiler error (name resolution doesn't require access to this, though I can see how a compiler implementation might require it) - it's a separate bug though. Microsoft has confirmed this to be a bug and have apparently prepared a fix for the next release.

like image 153
ex0du5 Avatar answered Nov 06 '22 01:11

ex0du5


The following compiles fine. It seems to me that this must just be a VS bug with templates.

struct Foo {
    static void foo() {}
    void bar() {
        auto f = []() { foo(); };
        f();
    }
};
like image 2
bames53 Avatar answered Nov 06 '22 01:11

bames53