【问题标题】:Problems with nested lambdas in VC++VC++ 中嵌套 lambda 的问题
【发布时间】:2011-09-14 14:03:21
【问题描述】:

有谁知道为什么这段代码不能用 VC++ 2010 编译

class C
{
public:
    void M(string t) {}
    void M(function<string()> func) {}
};

void TestMethod(function<void()> func) {}

void TestMethod2()    
{
    TestMethod([] () {
        C c;            
        c.M([] () -> string { // compiler error C2668 ('function' : ambiguous call to overloaded function)

             return ("txt");
        });
    });
}

更新:

完整代码示例:

#include <functional>
#include <memory>
using namespace std;

class C
{
public:
  void M(string t) {}
  void M(function<string()> func) {}
};

void TestMethod(function<void()> func) {}

int _tmain(int argc, _TCHAR* argv[])
{
   TestMethod([] () {
      C c;
      c.M([] () -> string { // compiler erorr C2668 ('function' : ambiguous call to overloaded function M)
          return ("txt");
      });
    });
    return 0;
}

【问题讨论】:

  • 好的。那么C2668怎么说呢?不是每个人都在使用那个编译器。
  • 对不起。我在上面添加了错误描述
  • 我在下面发布的版本可以用 g++ 干净地编译。您应该发布您的实际代码。
  • 您的代码仍然不完整。要使用string,您应该#include &lt;string&gt;。此外,与标准兼容的main 具有签名int main()int main(int, char*[])。其他一切都是编译器特定的。
  • 顺便说一句,到目前为止你还尝试过什么?

标签: visual-c++ compiler-construction lambda


【解决方案1】:
【解决方案2】:

您没有发布错误消息,因此通过查看我的水晶球,我只能得出结论,您遇到了这些问题:

缺少#includes

你需要在顶部

#include <string>
#include <functional>

缺少姓名限定

你要么需要添加

using namespace std;

using std::string; using std::function;

或 标准::函数... 标准::字符串 ...

缺少函数main()

int main() {}

适用于 g++

foo@bar: $ cat nested-lambda.cc

#include <string>
#include <functional>

class C
{
public:
    void M(std::string t) {}
    void M(std::function<std::string()> func) {}
};

void TestMethod(std::function<void()> func) {}

void TestMethod2()    
{
    TestMethod([] () {
        C c;            
        c.M([] () -> std::string { // compiler error C2668 
             return ("txt");
        });
    });
}

int main() {
}

foo@bar: $ g++ -std=c++0x nested-lambda.cc

工作正常。

【讨论】:

  • 我发布了错误号(现在也发布了错误消息)作为源代码注释。我的问题是,编译器不知道应该使用 M 的哪个方法重载。但我不知道为什么。您说代码用 g++ 编译正确,所以可能是 VC++ 编译器错误。
  • 或 g++ 中的错误,也许不应该,但 g++ 会;虽然对于我的生活,我看不出为什么 VC++ 不能处理它。 g++ 也有错误stackoverflow.com/questions/7214623/…
  • @Shaun Wilde:lambda 的主体是 compound-statement,这对于普通函数也是如此,其主体也是 compound-statement(参见附件 A:语法摘要)。当然,每个重要的软件都有错误;)
  • @phresnal - 上面的代码(有问题的正文)不像提问者所描述的那样在 VC++ 中编译。是否应该像在 g++ 中那样,如果是这样,那么它是 vc++ 中的错误吗?
  • @Shaun Wilde:这还取决于 OP 未发布的其余代码。但是,我想这确实是 VC++ 中的一个错误。
猜你喜欢
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多