从其他文件C ++中的模板类调用静态方法

时间:2017-05-17 10:18:41

标签: c++ templates static-methods

我希望有一个类 Sorings ,在其中通过静态方法和模板实现一些排序方法。我已阅读here,应在.h文件中实现静态模板方法。这是我的代码:

Sortings.h

#ifndef SORTINGS_H_
#define SORTINGS_H_

template <class T>
class Sortings {
public:
    static void BubbleSort(T a[], int len, bool increasing)
    {
        T temp;
        for(int i = len-1; i >= 1; i--)
            for(int j = 0; j<= i-1; j++)
                if(increasing ? (a[j] > a[j+1]) : (a[j] < a[j+1])) {
                    temp = a[j+1];
                    a[j+1] = a[j];
                    a[j] = temp;
                }
    };
};

#endif /* SORTINGS_H_ */

Sortings.cpp

#include "Sortings.h"
//empty?

Practice.cpp

#include <iostream>
#include "Sortings.h"
int main() {
    int a[6] = {4,5,2,11,10,16};
    Sortings::BubbleSort<int>(a,6,true);
    return 0;
}

但它返回以下错误:(这些行是这样的,因为我已经在Practice.cpp中评论了所有其余的错误)

Description Resource    Path    Location    Type
'template<class T> class Sortings' used without template parameters PracticeCpp.cpp /PracticeCpp/src    line 41 C/C++ Problem
expected primary-expression before 'int'    PracticeCpp.cpp /PracticeCpp/src    line 41 C/C++ Problem
Function 'BubbleSort' could not be resolved PracticeCpp.cpp /PracticeCpp/src    line 41 Semantic Error
Symbol 'BubbleSort' could not be resolved   PracticeCpp.cpp /PracticeCpp/src    line 41 Semantic Error

我不明白问题所在。你能帮我理解什么是错的:概念上还是/和句法上的?

我正在运行Eclipse Neon.3 Release(4.6.3)

3 个答案:

答案 0 :(得分:1)

你模仿了类,而不是静态方法!

因此,您需要使用Sortings::BubbleSort<int>

,而不是使用Sortings<int>::BubbleSort

答案 1 :(得分:1)

在调用中,您将模板添加到函数中,但是您在类上声明了模板。

Sortings::BubbleSort<int>(a,6,true);

应该成为

Sortings<int>::BubbleSort(a,6,true);

答案 2 :(得分:1)

template <class T>
class Sortings {

模板参数适用于类,而不适用于方法。因此,您必须将其称为Sortings<int>::BubbleSort(a,6,true);。换句话说,没有名为Sortings的类型。相反,类型为Sortings<int>

此外,您不需要Sortings.cpp,因为所有内容都在头文件中。

虽然没有直接在问题中提问,但我认为你这里不需要上课。命名空间内的简单模板化静态方法可以正常工作。有点像这样:

namespace Sorting {

template<class T>
static void BubbleSort(T a[], int len, bool increasing) {
   // ...
}

}

然后你可以拨打Sorting::BubbleSort<int>(a,6,true)