2012-03-29 196 views
1

我试图编译下面的程序:我错过了什么?

#include<functional> 
#include<iostream> 

int main(int argc, char* argv[], char* env[]) { 
    std::function<int(int, int)> f = [i, &j] { return i + j; }; 
    std::cout << f(5, 5); 
} 

为什么我收到以下错误:

a.cc:17:3: error: \u2018function\u2019 is not a member of \u2018std\u2019 

即使我有“自动”的编译器替换它抱怨说,“F”不会命名一个类型。我尝试了GCC 4.4.3和4.6.2。

+2

这可能有所帮助:http://stackoverflow.com/questions/9408082/c11-gcc-4-6-2-stdmove。 – 2012-03-29 16:46:26

回答

6
std::function<int(int, int)> f = [i, &j] { return i + j; }; 

这是错误的语法。

你真正想要写的是这样的:

std::function<int(int, int)> f =[](int i, int j) { return i + j; }; 

或者,如果你想使用auto,则:

auto f =[](int i, int j) { return i + j; }; 

使用-std=c++0x选项使用gcc-4.6.2编译这段代码。

0

Polymorphic wrappers for function objects在C++ 11中是新的。要在支持C++ 0x(C++ 11草稿版本)的4.7之前的GCC安装中使用这些功能,您需要使用-std=c++0x开关进行编译(请参阅here)。

对于GCC v4.7,即切换到-std=c++11(请参阅here)。