2014-03-25 44 views
1

的成員函數我是新來的C++和Im學習使用模板。 我想使模板類與2個模板參數,並且從類專門的單個成員函數,對於其中所述第二模板參數是模板上的指針類型的第一個參數的矢量的情況。我想的是我的嘗試會更加清楚的例子:C++專門爲載體

//Container.h: 

template<class T , class CONT > 
class Container { 

private: 
    CONT container; 
    T someData; 
public: 
    void foo(); 
}; 

,我嘗試了特化了的std ::向量是:

//Container.cpp 

template<class T> 
void Container<T, std::vector<T*> > ::foo(){ 
    cout << "specialized foo: " << container.pop_back(); 
    } 

template<class T, class CONT > 
void Container<T, CONT > ::foo(){ 
    cout << "regular foo: " << container.pop_back()); 
} 

,但我得到這些erors:

error C3860: template argument list following class template name must list parameters in the order used in template parameter list 
error C2976: 'Container<T,CONT>' : too few template argument 

Container類的使用必須是該第一參數是某種類型的,並且第二個是一個STL容器,載體或列表。例如:

Container<int, vector<int*> > c; 
c.foo(); 

我是什麼東錯了?

+3

除了語法錯誤,你不能專注函數模板部分,所以這種方法不工作。 –

回答

1

正確語法類模板來定義成員函數是

template<class T, class CONT > 
void Container<T, CONT>::foo() 
{ 
    cout << "specialized foo:" ; 
} 

FOO()函數未過載和重新定義。重新定義foo()函數也會給出錯誤。您不能在返回類型的基礎上重載函數。 std :: vector的特化不正確。 < <運營商也應該重載你can'y直接使用這樣

cout << container.pop_back();

+0

我編輯了語法錯誤,除此之外,你可以假定operator <<重載,我只是想表明foo使用容器對象的成員函數。 – user3066442

1

您可以使用基於策略的設計。現在有這個許多變化,但一個簡單的例子是這樣這樣

#include <iostream> 
#include <vector> 

using namespace std; 

template<typename T, class CONT> 
struct foo_policy { 
    static inline void execute() { 
     cout << "regular foo: \n" ; 
    } 
}; 

template<typename T> 
struct foo_policy<T, std::vector<T*>> { 
    static inline void execute() { 
     cout << "specialized foo: \n" ; 
    } 
}; 

template<class T , class CONT > 
class Container 
{ 
private: 
    CONT container; 
    T someData; 
public: 
    void foo() 
    { 
     foo_policy<T, CONT>::execute(); 
    } 
}; 

int main() 
{ 
    Container<int, std::vector<int>> a; 
    Container<int, std::vector<int*>> b; 
    a.foo(); 
    b.foo(); 
    return 0; 
} 

Here's a demo。在另一種情況下,你可以從foo_policy類派生容器和使用基本成員的功能(但有更多的複雜影響)

+0

謝謝,我想它會完成這項工作,但我認爲有一個更直接的方法來實現這一目標。 – user3066442