Function template specialization with a template class [duplicate]

两盒软妹~` 提交于 2019-11-30 15:38:29

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.

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) {}

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