Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template specialization with a template class [duplicate]

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?

like image 948
Tim Avatar asked Feb 18 '23 13:02

Tim


1 Answers

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.

like image 100
Sebastian Mach Avatar answered May 01 '23 21:05

Sebastian Mach