Function template specialization with template class

Possible duplicate:
partial specialization of function template

I canโ€™t find a solution for my problem, because if I search for the keywords that I came up with, it will give me solutions that are suitable for different problems. I understand that this should be asked earlier, just canโ€™t find a solution.

Suppose I have a function template:

template<class any> print(any value); 

I can specialize it to say a int :

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

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

Specializing in such a function:

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

It will generate the following error (MinGW g ++):

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

Note that the print function is just an example.

How can i solve this?

+4
source share
3 answers

There is a general workaround in which the template function simply delegates the task to the member functions of the class template:

 #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 up with a simple function overload (as suggested by ecatmur and Vaughn Cato), do it.

+5
source

Do not try to specialize function templates. Use overload instead

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

and

 template<class any> void print(vector<any> value) {} 
+2
source

Partial specialization of the template template is not allowed, as this will lead to violations of the rules with one definition. You can usually use overload:

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

Source: https://habr.com/ru/post/1444822/


All Articles