簡體   English   中英

具有函數聲明/原型和定義的C ++模板

[英]C++ Templates with function declaration/ protype and definition

我是模板的新手, 正在閱讀它們,模板 找到了不錯的視頻教程

此外,我知道模板有兩種類型,即類和函數模板。 但是,在我的代碼片段中,我只想使用函數模板而不是類模板,但是我想擁有一個利用模板的函數聲明和定義。 在函數定義和聲明中為模板使用相同的代碼似乎有點奇怪(我在cpp網站上讀到了一個線程,但是現在只能發布兩個鏈接)。

這是將模板與函數聲明和定義一起使用的正確語法嗎?

  • 一種。

這是合並代碼的片段:

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){...}

如果您以正確的方式調用它,那么語法對我來說效果很好:

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

觀看現場演示

不過請注意:
簡單地調用該方法而不指定實際的數組尺寸,編譯器將無法自動推導這些尺寸:

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");

請參閱替代演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM