【问题标题】:Function that takes templated length parameter采用模板化长度参数的函数
【发布时间】:2022-01-11 07:26:15
【问题描述】:

我有一个自定义数组类

template <typename T, unsigned L>
class Array
{
    T m_buff[L];
};

我的目标是声明一个函数,该函数将获取 Array 类的副本并使用其值返回所有元素的总和。
问题是代码只为定义为int sum(Array&lt;int, 3&gt; a) 的函数编译,而不为定义为int sum(Array&lt;int&gt; a) 的函数编译。

【问题讨论】:

  • template&lt;typename T, unsigned L&gt; T sum(const Array&lt;T,L&gt; &amp;array) { /* calc, return sum */}。您可能需要考虑使用标准库中的类型(例如模板化的std::array)和标准算法(例如std::accumulate())来将其中的元素相加。
  • 我知道标准数组实现,但我想自己做一个。

标签: c++ templates


【解决方案1】:

不适用于定义为 int sum(Array a) 的函数。

那是因为Array&lt;int&gt; 不是有效类型。您的Array 模板需要两个参数,而不是一个。

您正在寻找的只是另一个模板函数:

template<unsigned size> int sum(const Array<int, size> &a)
{
   // Function code here:
}

至于如何编写代码:只需想想你的代码需要是什么,如果你是Array&lt;int, 3&gt;,或者,也许是Array&lt;int, 100000&gt;,并将3100000替换为size/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多