C ++ 11 std :: function是否限制了函数指针可以拥有的参数个数?

时间:2012-04-10 15:51:18

标签: 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);

似乎工作正常。

1 个答案:

答案 0 :(得分:37)

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

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

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

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

来使用任意数量的参数