2013-04-15 45 views
7

我創建一個模板類,並將T作爲默認類型參數傳遞。但是這會導致編譯失敗。任何人都可以解釋發生什麼謝謝!爲什麼將T從外部模板作爲默認參數傳遞給std :: function會導致編譯錯誤?

PS。我使用的編譯器是VS2012。

#include <functional> 

using namespace std; 

template <typename T = void()> 
struct delegate 
{ 
    typedef function<T> function_t; 

    function_t f; 
}; 

int main() 
{ 
    delegate<> d; 

    return 0; 
} 

編譯器輸出:

1>.\Microsoft Visual Studio 11.0\VC\include\functional(554): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>' 
1>   with 
1>   [ 
1>    _Tx=void (__cdecl *)(void) 
1>   ] 
1>   test.cpp(12) : see reference to class template instantiation 'std::function<_Fty>' being compiled 
1>   with 
1>   [ 
1>    _Fty=void (__cdecl *)(void) 
1>   ] 
1>   test.cpp(17) : see reference to class template instantiation 'delegate<>' being compiled 
1>.\Microsoft Visual Studio 11.0\VC\include\functional(555): error C2504: 'type' : base class undefined 
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C2027: use of undefined type 'std::_Get_function_impl<_Tx>' 
1>   with 
1>   [ 
1>    _Tx=void (__cdecl *)(void) 
1>   ] 
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C2146: syntax error : missing ';' before identifier '_Mybase' 
1>.\Microsoft Visual Studio 11.0\VC\include\functional(558): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
+2

看起來像一個MSVC編譯器錯誤。在g ++ 4.7.0下編譯得很好。 – Yuushi

+0

@Yuushi真的嗎?非常感謝你。我只是想做一個默認版本的函數<>,它相當於函數。 –

+1

編譯器正在將'T'變成void(*)()而不是'void()',然後將'T'傳遞給'std :: function',這不是一個有效的類型傳遞給'std: :function'。你或許可以編寫一個解決方案,它可以將'A(B ...)'或'A(*)(B ...)'作爲一個參數,並將一個'template class F'作爲另一個,並且'F 「如果你真的想解決這個問題。 – Yakk

回答

2

正如你的問題的評論指出:這只是在Visual Studio中的錯誤,並沒有什麼毛病你的C++代碼。 @ Stephan-T-Lavavej說他將它作爲DevDiv#671343提交。

假設@ Yakk的診斷是正確的(MSVC正確處理T作爲void(*)()代替void()),我以前提出的

typedef function<typename remove_pointer<T>::type> function_t; 

的「可能的解決方法」,而是@JoshPeterson下面評論,錯誤仍然出現在VS2013即使有這種變化,所以它不是實際上是的一種解決方法。

+1

使用Visual Studio 2013我用'typedef函數 :: type> function_t;'替換'typedef函數 function_t;'並且問題仍然存在。 –

+0

我剛剛在Visual Studio 2013 Update 1中嘗試了原始問題和建議的解決方法。但是,它們都不會編譯。 –

相關問題