2015-09-13 47 views
1

我在下面有這個簡單的代碼,一個帶有2個類型參數的模板。如果我宣佈我的課與同類型(如BidirectionalMap<int,int>),我收到一個錯誤:已經定義了相同類型的C++模板成員函數

int BidirectionalMap<T,S>::operator [](T) const' : member function already defined or declared 

這裏是我的模板代碼:

template <class T, class S> 

class BidirectionalMap{ 
    int count(T t){ 
     return 1; 
    } 
    int count(S s){ 
     return 1; 
    } 
}; 
+0

如果'T'和'S'是同一類型,你想要什麼? (目前'count'具有相同的實現,但它只是例如?) – Jarod42

+0

是的,這只是一個例子不要混淆你們,計數的實施並不重要,我只需要使用計數的地圖值,這也是關鍵 –

回答

3

你有錯誤是正常的,因爲替換之後你有

template <> 
class BidirectionalMap<int, int> 
{ 
    int count(int t){ return 1; } 
    int count(int s){ return 1; } // Duplicated method 
}; 

爲了解決這個問題,你可以提供部分特化:

template <class T> 
class BidirectionalMap<T, T> 
{ 
    int count(T t) { return 1; } 
}; 
相關問題