c++ - C++11 std::function 是否限制函数指针可以具有的参数数量?

标签 c++ c++11 function-pointers std

我正在使用 Visual Studio 11 测试版,我很好奇在我的类中存储 std::function 对象时出现的编译错误。

typedef std::function<void (int, const char*, int, int, const char*)> MyCallback;

在我的课上,

MyCallback m_callback;

这编译得很好。如果我在列表中再添加一个参数,它会失败。

typedef std::function<void (int, const char*, int, int, const char*, int)> MyCallback;

失败是:

>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(535): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>'
1>          with
1>          [
1>              _Tx=void (int,const char *,int,int,const char *,int)
1>          ]
1>          f:\development\projects\applications\my.h(72) : see reference to class template instantiation 'std::function<_Fty>' being compiled
1>          with
1>          [
1>              _Fty=void (int,const char *,int,int,const char *,int)
1>          ]
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(536): error C2504: 'type' : base class undefined
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(539): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>'
1>          with
1>          [
1>              _Tx=void (int,const char *,int,int,const char *,int)
1>          ]
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(539): error C2146: syntax error : missing ';' before identifier '_Mybase'
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional(539): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

这是一个动态链接库,它正在准备数据以传递给另一个应用程序。我当然可以重新设计数据的格式,以便可以用更少的参数传递它,但我想知道为什么会看到这个限制?

切换回c风格的函数指针,

 typedef void (*MyCallback)(int, const char*, int, int, const char*, int);

似乎工作正常。

最佳答案

此限制由 Visual Studio 中的实现设置。

std::function 的 C++ 规范没有任何限制。 std::function 使用可变参数模板来处理任意数量的参数。实现可能有一个限制,例如,模板实例化嵌套限制,但它应该很大。例如,规范建议 1024 作为支持的最小嵌套深度,而 256 作为一个函数调用中允许的参数的最佳最小值。

Visual Studio(从 VS11 开始)没有可变参数模板。他们在 VS11 中最多模拟 5 个参数,但您可以将其更改为最多 10 个。通过在项目中定义 _VARIADIC_MAX 来做到这一点。这会大大增加编译时间。

更新:VS 2012 Nov CTP 添加了对可变参数模板的支持,但标准库尚未更新以使用它们。更新后,您应该能够在 std::function 中使用任意数量的参数。

关于c++ - C++11 std::function 是否限制函数指针可以具有的参数数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092074/

相关文章:

c++ - 如何将 xor 加密从使用 std::string 转换为仅使用 char 或 char *?

c++ - 警告函数的调用者必须处理

c++ - 哈希顶点的最佳方法

c++ - 是否可以在 C++ 中匹配递归整数模板参数?

将具有不同指针类型的函数指针转换为参数

c++ - 将函数指针绑定(bind)到 boost::function 对象

c++ - 重构使用 if 语句的重复范围检查

c++ - 为什么不调用成员变量的移动构造函数?

c++ - 使用传递函数指针调用 _beginthreadx

c++ - C中main函数的第四个参数指向什么?