C ++ method template specialization for only one index

I would like to do specialized specialization for only one class index. For example, in the following code, I want to create a specialization whenever the first class is int, regardless of what the second class is. Is there any way to implement this?

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) { ... } 
+4
source share
2 answers

You can, but you need to specialize the entire class "myclass", and not just one method "myfunc". Here is an example:

 #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; } 
+5
source

You can do this, but you must specialize myclass for <int ,? > case. This means repeating each definition in both cases. Depending on what you want, you can get away with inheritance or the like to avoid code duplication. Without additional information about what you intend, the answer is:

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

You can get a better answer with more details, there are many possibilities in the world of templates.

0
source

All Articles