Search code examples
c++functiontemplatesspecializationpartial-specialization

Function template specialization with a template class


Possible Duplicate:
partial specialization of function template

I can't find anywhere a solution for my problem, because if I search with the keywords I come up with would give me solutions suited for different problems. I understand that this must been asked before, just can't find a solution.

Suppose I have a function template:

template<class any> print(any value);

I can specialize it like this for let's say a int:

template<> print<int>(int value)
{
    std::cout << value;
}

But now the problem, I want it to work with a vector as well. Since the vector class is a template class it becomes difficult.

Specializing the function like this:

template<class any> print<vector<any> >(vector<any> value) {}

Will generate the following error (MinGW g++):

FILE: error: function template partial specialization 'print<vector<any> >' is not allowed

Note that the function print is just an example.

How can I solve this?


Solution

  • There is a general workaround in which the function-template just delegates the job to class template member functions:

    #include <vector>
    #include <iostream>
    
    template <typename T> struct helper {
        static void print(T value) { std::cout << value; }
    };
    template <typename T> struct helper<std::vector<T>> {
        static void print(std::vector<T> const &value) { }
    };
    
    template <typename T>
    void print (T const &value) {
        // Just delegate.
        helper<T>::print (value);
    }
    
    
    int main () {
        print (5);
        std::vector<int> v;
        print (v);
    }
    

    However, if you can come by with simple function overloading (as suggested by ecatmur and Vaughn Cato), do so.