开发者

C++ method template specialization for only one index

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 k开发者_运维百科ey, V value) {
...
}


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜