可以使用函子作为 std::function 的模板参数

Is possible to use functor as template parameter to std::function?

本文关键字:function 参数 std 可以使      更新时间:2023-10-16

我正在尝试查找用于编译此示例 c++ 代码的 g++ 编译器参数:

#include <stdio.h>
#include <functional>
struct mystruct
{
    int a;
    int operator()(int y) { return y + 1; }
};
int main()
{
    std::function<mystruct> foo;
    return 0;
}

在 cpp 引用中写道,std::函数模板参数可以是"...或其他函数对象"。我从事包含多个 std::function 的大型项目,并且可以使用 g++ 构建项目。我正在尝试在VS2015下构建它,但是此类代码的编译器抱怨:

错误 C2027:使用未定义的类型"std::_Get_function_impl<_Fty>" 跟 [ _Fty=肌理结构 ]

当我尝试使用 -std=c++11 在 g++ 下编译上面的小样本时,它也包括:

错误:聚合"std::函数 a"的类型不完整,无法定义

所以我认为在我们的大型可构建项目中,g++ 可能已经切换了一些提供这种功能的扩展。

您可能将

模板参数与要存储的函数对象混淆了。我相信你想写的是

std::function<int(int)> foo{mystruct{}};

答案是函子不能是其他函子的模板参数。感谢所有帖子。