具有函数声明/原型和定义的C++模板

问题描述:

我是新来的模板,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

如果你调用它的正确方法,语法很适合我:

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失败。