Function template specialization with a template class [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-18 17:25:42

问题


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?


回答1:


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.




回答2:


Don't try to specialize function templates. Use overloading instead

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

and

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



回答3:


Function template partial specialization is not allowed because it would lead to one-definition-rule violations. You can usually just use an overload:

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


来源:https://stackoverflow.com/questions/13291270/function-template-specialization-with-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!