2014-09-27 109 views
1

我是新來的模板,was reading up on themfound a great video tutorial on them具有函數聲明/原型和定義的C++模板

此外,我知道有兩種類型的模板,類和函數模板。然而,在我的代碼片段中,我只想使用函數模板而不是類模板,但我想要使用模板的函數聲明和定義。在函數定義和聲明中使用相同的模板代碼似乎有點不可思議(我在cpp網站上閱讀了此主題,但我現在只能發佈兩個鏈接)。

這是使用帶有函數聲明和定義的模板的正確語法嗎?

  • A.

這裏是統一的代碼片段:

class GetReadFile { 
public: 
    // Function Declaration 
    template <size_t R, size_t C> // Template same as definition 
    bool writeHistory(double writeArray[R][C], string path); 
}; 

// Function Definition 
template <size_t R, size_t C>  // Template same as declaration 
bool GetReadFile::writeHistory(double writeArray[R][C], string path){...} 
+0

這是正確的,或者你可以直接定義函數內聯(在類內)。 – vsoftco 2014-09-27 16:45:21

回答

0

如果你調用它的正確方法,語法很適合我:

GetReadFile grf; 
double array[5][8];  
grf.writeHistory<5,8>(array,"blah"); 

請參閱live demo

注意雖然:
簡單地調用,而無需指定實際數組維度該方法中,這些不能由編譯器自動地推導出:

grf.writeHistory(array,"blah"); 

main.cpp:24:34: error: no matching function for call to 'GetReadFile::writeHistory(double [5][8], const char [5])' 
    grf.writeHistory(array,"blah"); 
          ^
    ... 
main.cpp:10:10: note: template argument deduction/substitution failed: 
main.cpp:24:34: note: couldn't deduce template parameter 'R' 
grf.writeHistory(array,"blah"); 

alternate demo失敗。