2016-10-05 6 views
0

私は、いくつかの値型のstdベクトルの関数のテンプレートコレクションをしようとしています。C++のカスタムソートアルゴリズムのテンプレートを使用した初心者の問題

だから私は、ソートアルゴリズムの使用を開始し、このようにそれをやった:

template <typename T> 

struct SortReturn{ 
    std::vector<T> values; 
    IntVector indexes; 
}; 

class FunctionCollection 
{ 
public: 
    FunctionCollection(); 

    static SortReturn<T> QuickSort(std::vector<T>, bool ascending = true); 

private: 

    static SortReturn QuickSortRecursive(SortReturn array, int left, int right, bool ascending); 

}; 

しかし、これはコンパイルできないし、それは私に

/ホーム/ ariela/ownCloud /ワークスペース/ FunctionDev/functioncollectionを与えます。 h:18:error: 'T'がこのスコープで宣言されていません。 static SortReturn QuickSort(std :: vector、bool ascending = true); ^

私は間違っていますか?

+0

ようになるはずですここで間違いを指摘する単純な答えを得るだけです。 – Hayt

+1

テンプレートは、最初の構造体のみを参照します。 2番目の構造体(クラス)もテンプレート化されており、独自のテンプレート定義が必要です。しかし、独自の関数型ソートを行う前に、さらに多くのことが必要になります。 –

答えて

0

あなたは、構造体とクラスの両方をテンプレートする必要があります、あなたも必要になりますそれはテンプレートタイプだとQuickSortRecursiveにごSortReturnオブジェクトを渡すだけでなく、それはテンプレートタイプだと、オブジェクトを返すために、コードを使用すると、チュートリアルを開始するか、代わりのテンプレートに案内している場合、それはおそらくより多くの助け

template <typename T> 
struct SortReturn{ 
    std::vector<T> values; 
    IntVector indexes; 
}; 

template <typename T> 
class FunctionCollection 
{ 
public: 
    FunctionCollection(); 

    static SortReturn<T> QuickSort(std::vector<T>, bool ascending = true); 

private: 

    static SortReturn<T> QuickSortRecursive(SortReturn<T> array, int left, int right, bool ascending); 

}; 
+0

ありがとうございました!これはうまくいった! – aarelovich

0

template <…>宣言は、次の項目に対してのみ有効です。次の関数、構造体、またはクラス宣言/定義。

したがって、あなたがFunctionCollection前に2番目の1を追加する必要があります。

template <typename T> 
class FunctionCollection 
{ 
    … 

はまた、あなたはあなたのパラメータであなたのSortReturnTを追加し、型を返す必要があります。

これは、(私的な)名前空間のクラスを誤って使用していると言われています。テンプレートはdetailまたはinternalのような名前空間に実装を入れて、ヘッダのいずれかの方法で定義する必要があるので、この場合には

template <typename T> 
struct SortReturn{ 
    std::vector<T> values; 
    IntVector indexes; 
}; 

namespace internal { 
    template <typename T> 
    SortReturn<T> QuickSortRecursive(std::vector<T> array, int left, int right, bool ascending){ 
     … 
    } 
} 


template <typename T> 
SortReturn<T> QuickSort(std::vector<T> arr, bool ascending = true) { 
    return internal::QuickSortRecursive(arr, 0, arr.size(), ascending); 
} 
+0

うん、私はこれを実現し始めていた。 – aarelovich