2012-04-10 70 views
14

我正在使用Visual Studio 11測試版,我對編譯錯誤感到好奇,因爲我在類中存儲了一個std :: function對象。C++ 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); 

似乎很好地工作。

回答

37

此限制由Visual Studio中的實現設置。

std::function的C++規範沒有任何限制。 std::function使用可變模板來處理任意數量的參數。基於例如模板實例化嵌套限制,實現可能具有限制,但它應該很大。例如,該規範建議將1024作爲支持的最小嵌套深度,並將256作爲允許在一個函數調用中使用的參數的最小值。

Visual Studio(自VS11起)沒有可變參數模板。他們在VS11中最多可以模擬5個參數,但可以將其更改爲10.通過在項目中定義_VARIADIC_MAX來實現此目的。這可以大大增加編譯時間。

更新:VS 2012 Nov CTP增加了對variadic模板的支持,但標準庫尚未更新使用它們。一旦更新,你應該可以使用盡可能多的參數,只要你想用std::function

+1

正確答案。 STL自己在2012年的GoingNative上也看到了[Magic && Secrets](http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/STL11-Magic-Secrets),他提到了這一次或兩次。 – Xeo 2012-04-10 16:01:18

+0

有趣的事情。我記得實現可變參數模板只是g ++方面的一小部分工作。 – 2012-04-10 16:04:56

+0

非常好,那回答我的問題,謝謝! – BZor 2012-04-10 16:12:14