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).
Is this the correct syntax for using a template with a function declaration and definition?
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.