2011-02-11 80 views
11

我試圖創建一個模板類,它存儲了一個模板函數的函數指針,但在Visual Studio 2008中遇到了一個編譯錯誤。我創建了一個簡化的測試用例對於它(見下文),它仍然無法在VS2008中編譯,但似乎在我試過的在線Comeau和在線GCC編譯器上成功編譯。在Visual Studio 2008中編譯錯誤指向模板函數

我看到的錯誤是:

error C2436: 'func' : member function or nested class in constructor initializer list 
temp.cpp(21) : while compiling class template member function 'test_class<T>::test_class(T (__cdecl &))' 
1>  with 
1>  [ 
1>   T=int (const int &) 
1>  ] 

使用非模板函數的工作原理相同的測試。簡而言之,有沒有人知道這個問題的解決方法,或者如果VS2008期待這種不同的語法?

感謝,

傑裏

template<class T> 
T template_function(const T& arg) 
{ 
    return arg; 
} 

int non_template_function(const int& arg) 
{ 
    return arg; 
} 

template<class T> 
class test_class 
{ 
public: 
    test_class(const T& arg) : func(arg) {} 
private: 
    T func; 
}; 

template<class T> 
void create_class(const T& arg) 
{ 
new test_class<T>(arg); 
} 

int main() 
{ 
    create_class(&template_function<int>); //compile fails unless this is commented out 
    create_class(&non_template_function); 
    return 0; 
} 
+0

+1爲問題,寫得很好,很好的最小工作示例。無法權威回答,但錯誤消息中的__cdecl設置關於鏈接的警報鈴聲。 – Flexo 2011-02-11 17:52:48

回答

0

在我看來,像test_class和create_class中的「const T & arg」是你的問題。將它們改爲簡單的「T arg」似乎可以使事情變得順利。

+0

就是這樣,謝謝!不知道爲什麼使用模板函數而不是非模板函數失敗,但是這種變化對兩者都有效。 – Jerry 2011-02-11 19:48:48

1

這似乎是一個編譯器錯誤,因爲它實際上認爲你試圖調用該函數,而不是初始化的。

我沒有VS C++編譯器,但在宣佈T作爲指針可以解決此問題:

template<class T> 
class test_class 
{ 
public: 
    test_class(const T& arg) : 
     func(&arg) 
    { 
    } 

private: 
    T *func; 
}; 


template<class T> 
void create_class(const T& arg) 
{ 
    new test_class<T>(arg); 
} 

int main() 
{ 
    create_class(template_function<int>); //compile fails unless this is commented out 
    create_class(non_template_function); 
} 
2

修復兩處;

T* func; //make this pointer type! 

,並

create_class(template_function<int>); //remove '&' 
create_class(non_template_function); //remove '&' 

完成!