4

I'd like to perform a template specialization for only one index of a class. 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 a 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) {
...
}
entitledX
  • 670
  • 1
  • 7
  • 13
  • similar question: [C++ partial method specialization](http://stackoverflow.com/questions/1535816/c-partial-method-specialization) – Amro Mar 23 '13 at 01:53

2 Answers2

5

You can, but you need to specialize the whole class "myclass", not just single 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;
}
Sergey Sirotkin
  • 1,668
  • 11
  • 7
0

You can do that, but you have to specialize myclass for the < int, ? > case. This means repeating every definition in both cases. Depending exactly on what you want, you may be able to get away using inheritance or similar to avoid code duplication. With no further detail on 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 may get a better answer with more specific detail, there are lots of opportunities in the template world.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • I am trying to implement my own hash table where key is of class K and the value is of class V. However, I was hoping to specialize different hash functions for various types of K. In this case, class V can still be arbitrary. – entitledX Sep 13 '11 at 03:50
  • You should take a look at how C++11 unordered_(hash)sets and maps do that, or the Boost implementation of them: http://www.boost.org/doc/html/unordered.html – K-ballo Sep 13 '11 at 03:55