我正在使用 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/