简体   繁体   English

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

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

I'm new to templates, was reading up on them and found a great video tutorial on them . 我是模板的新手, 正在阅读它们,模板 找到了不错的视频教程

Furthermore, I know that there are two types of templates, class and function templates. 此外,我知道模板有两种类型,即类和函数模板。 However, in my snippet of code I only wanted to use a function template instead of a class template, but I wanted to have a function declaration and definition that makes use of the template. 但是,在我的代码片段中,我只想使用函数模板而不是类模板,但是我想拥有一个利用模板的函数声明和定义。 It seems a little weird to have the same code for the template in the function definition and declaration (I read a thread on this on the cpp website, but I can only post two links right now). 在函数定义和声明中为模板使用相同的代码似乎有点奇怪(我在cpp网站上读到了一个线程,但是现在只能发布两个链接)。

Is this the correct syntax for using a template with a function declaration and definition? 这是将模板与函数声明和定义一起使用的正确语法吗?

  • A. 一种。

Here is the snippet of consolidated code: 这是合并代码的片段:

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

If you're calling it the right way, the syntax works well for me: 如果您以正确的方式调用它,那么语法对我来说效果很好:

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

See live demo . 观看现场演示

Note though: 不过请注意:
Simply calling that method without specifying the actual array dimensions, these can't be automatically deduced by the compiler: 简单地调用该方法而不指定实际的数组尺寸,编译器将无法自动推导这些尺寸:

grf.writeHistory(array,"blah");

Fails with 与失败

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

See the alternate demo . 请参阅替代演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM