【问题标题】:Implementing and calling a static method in a template class在模板类中实现和调用静态方法
【发布时间】:2011-09-10 03:03:02
【问题描述】:

我的代码如下:

插值.h

#ifndef INTERPOLATOR
#define INTERPOLATOR

#include <vector>
#include <utility>

template <class T>
class Interpolator
{
    public:
        static T InterpolateVector(const std::vector<std::pair<T, T>> & Vector, T At);

    private:
        static T GetBasisValue(T x);
};

template <class T>
T Interpolator::InterpolateVector(const std::vector<std::pair<T, T>> & Vector, T At) // Line #22
{
    // ...
}   // Line #25

// ...

#endif  // INTERPOLATOR

ma​​in.cpp

#include <vector>
#include <utility>
#include "Interpolator.h"

int wmain(int argc, wchar_t *argv[])
{
    std::vector<std::pair<float, float>> Measurements;
    Measurements.push_back(std::make_pair(0, 80.8));
    Measurements.push_back(std::make_pair(1, 80.4));
    Measurements.push_back(std::make_pair(3, 80.1));
    Measurements.push_back(std::make_pair(4, 79.6));

    float y2 = Interpolator<float>::InterpolateVector(Measurements, 2.0f);

    return 0;
}

当我构建此代码时,我收到以下错误消息:

C:...\Interpolator.h;第 22 行
错误 C2955:“插值器”:使用类 模板需要模板参数 列表

C:...\Interpolator.h;第 25 行
错误 C2244: “插值器::插值向量”: 无法将函数定义匹配到 现有声明

谁能告诉我我在这里做错了什么?

(IDE:Visual Studio 2010 Ultimate)

【问题讨论】:

    标签: c++ class templates methods static


    【解决方案1】:

    如错误信息中所写:'Interpolator' : use of class template requires template argument list

    你应该写:

    template <class T>
    T Interpolator<T>::InterpolateVector(const std::vector<std::pair<T, T>> & Vector, T At) // Line #22
    {
        // ...
    }   // Line #25
    

    【讨论】:

    • 成功了。非常感谢。代码中的其他一切都好吗?
    【解决方案2】:
    #ifndef INTERPOLATOR
    #define INTERPOLATOR
    
    #include <vector>
    #include <utility>
    
    template <class T>
    class Interpolator
    {
        public:
            static T InterpolateVector(const std::vector<std::pair<T, T> > & Vector, T At);
    
        private:
            static T GetBasisValue(T x);
    };
    
    template <class T>
    T Interpolator <T> ::InterpolateVector(const std::vector<std::pair<T, T> > & Vector, T At) // Line #22
    {
        // ...
    }   // Line #25
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多