2017-05-17 32 views
1

一个静态方法,我想有一类Sorings其中实现与模板的静态方法的一些排序方法。我已阅读here静态模板方法应该在.h文件中实现。这里是我的代码:从调用模板类从其他文件C++

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运行版本(4.6.3)

回答

1
template <class T> 
class Sortings { 

模板参数适用于类,而不是方法。所以你必须把它叫做Sortings<int>::BubbleSort(a,6,true);。换句话说,没有类型命名为Sortings。相反,该类型是Sortings<int>

而且你不需要Sortings.cpp,因为一切是头文件中。

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

namespace Sorting { 

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

} 

然后就可以调用Sorting::BubbleSort<int>(a,6,true)

+0

谢谢。我意识到我做了什么。它的工作原理,当然,当我将模板声明从类更改为方法时,我的原始代码工作。 – Veliko

1

你的模板类,而不是静态方法!

因此,而不是使用Sortings::BubbleSort<int>你需要使用Sortings<int>::BubbleSort

在电话会议上
1

,您添加模板的功能,但是你宣布对类的模板。

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

应该成为

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