在类中实例化C ++模板函数导致编译器错误

时间:2019-05-08 04:11:06

标签: c++ templates c++17

我多次在C ++类中编写模板函数,但从未遇到问题。但是,我正在尝试实现以下程序,该程序在设计上似乎与我之前做过的其他程序相同;但是,在这种情况下,我会收到一条编译消息instantiation of function 'Stats::suma<std::__1::vector<double, std::__1::allocator<double> > >' required here, but no definition is available. I am trying to use a template with the container so the user can pass c-style arrays, std :: vector s and std :: array`s。

// .hpp file
class Stats
{
public:
    template <class container> 
    double sum(const container &array);
};

// .cpp file
template <class container> double Stats::sum(const container &array)
{
    double summation = 0.0;
    for (unsigned long i = 0; i < array.size(); i++)
    {
        summation += array[i];
    }
    summation = summation / array.size();
    return summation;
}

// main.cpp file
Stats q;
std::vector<double> arr = {3.7, 5.9, 15.3, 22.1, 9.87};
double result = q.sum(arr);

该消息显然似乎表明编译器未将array变量识别为std::vector,但是我不确定如何解决此问题。我想念什么?

0 个答案:

没有答案
相关问题