【问题标题】:C++ Templates with function declaration/ protype and definition具有函数声明/原型和定义的 C++ 模板
【发布时间】:2014-11-22 11:42:52
【问题描述】:

我是模板的新手,was reading up on themfound a great video tutorial on them

此外,我知道有两种类型的模板,类模板和函数模板。但是,在我的 sn-p 代码中,我只想使用函数模板而不是类模板,但我希望有一个使用模板的函数声明和定义。在函数定义和声明中对模板使用相同的代码似乎有点奇怪(我在 cpp 网站上阅读了一个关于此的主题,但我现在只能发布两个链接)。

这是使用带有函数声明和定义的模板的正确语法吗?

  • 答.

这里是合并代码的sn-p:

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

【问题讨论】:

  • 没错,也可以直接定义函数inline(类内部)。

标签: c++ templates


【解决方案1】:

如果你用正确的方式称呼它,那么语法对我来说很有效:

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

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多