函数不是 STD 的元素

function is not an element of std

本文关键字:元素 STD 函数      更新时间:2023-10-16

我在gcc下编译代码时遇到了一些非常奇怪的错误。它告诉我std::function不存在。

我可以使用以下代码重新创建错误:

#include <functional>
#include <stdio.h>
void test(){ printf ("test"); }
int main() {
    std::function<void()> f;
    f = test;
    f();
}

如果我运行 gcc(来自 cygwin):(我的错误消息是德语,所以我翻译了它。在英语 gcc 上听起来可能不同)

$ gcc test.cpp
test.cpp: in function "int main(): 
test.cpp:7:3: Error: "function" is not an element of "std"« 
test.cpp:7:25: Error: "f" was not defined in this scope

使用 MSVC,它编译成功。请告诉我我在代码中做错了什么。

Johannes

编译为:

g++ test.cpp -std=c++0x

需要-std=c++0x,因为您使用的是 C++11 功能,否则g++ test.cpp就足够了。

确保您使用的是最新版本的 GCC。您可以按以下方式检查版本:

g++ --version
您需要

C++模式和C++11模式下编译。因此,您需要g++并将-std标志设置为 c++0x .

g++ test.cpp -std=c++0x

您也可以使用 gcc 4.7 开始的-std=c++11