2011-09-13 107 views
4

我想只爲一個類的一個索引執行模板專業化。例如,在下面的代碼中,無論第二個類是什麼,只要第一個類是int,就想創建一個專門化。有沒有辦法來實現這個?只有一個索引的C++方法模板專門化

template <class K, class V> 
class myclass { 
    public: 
     void myfunc(K,V); 
}; 

template <class K, class V> 
myclass<K,V>::myfunc(K key, V value) { 
... 
} 

template< ,class V> 
myclass<int,V>::myfunc(int key, V value) { 
... 
} 
+0

類似的問題:[C++部分方法專業化(http://stackoverflow.com/questions/1535816/c-partial-method-specialization) – Amro

回答

5

你可以,但你需要專門化整個班級「myclass」,而不是單一的方法「myfunc」。這裏有一個例子:

#include <iostream> 

template <typename K, typename V> 
class myclass { 
    public: 
     void myfunc(K key, V value) 
     { 
      std::cout << "non-specialized " << key << "->" << value << std::endl; 
     } 
}; 


template<typename V> 
class myclass<int, V> { 
    public: 
     void myfunc(int key, V value) 
     { 
      std::cout << "specialized " << key << "->" << value << std::endl; 
     } 
}; 

int main(int argc, char* argv[]) 
{ 
    myclass<int, char> instance; 
    instance.myfunc(10, 'a'); 

    myclass<long, char> instance2; 
    instance2.myfunc(10L, 'a'); 

    return 0; 
} 
0

你可以做到這一點,但你必須專注MyClass的爲< INT,? >案例。這意味着在兩種情況下重複每個定義。完全取決於你想要的東西,你可能能夠避免使用繼承或類似的方法來避免代碼重複。隨着你打算什麼沒有進一步的細節,答案是:

template< class K, class V > class myclass { general definition }; 
template< class V > class myclass< int, V >{ general definition }; 

您可能會得到更好的答案更具體的細節,有很多的模板世界的機會。

+0

我試圖實現自己的哈希表中鍵的類是K,值是類的V.但是,我希望專門爲不同類型的K的不同散列函數。在這種情況下,類V仍然可以是任意的。 – entitledX

+0

您應該看看C++ 11 unordered_(hash)集合和映射如何執行該操作或Boost實現:http://www.boost.org/doc/html/unordered.html –