使用模板类的函数模板特化

Tim*_*Tim 4 c++ templates function partial-specialization specialization

可能重复:
功能模板的部分特化

我找不到任何解决方案来解决我的问题,因为如果我用我想出的关键词进行搜索会给我一些适合不同问题的解决方案.我明白这之前一定是问过,只是找不到解决办法.

假设我有一个功能模板:

template<class any> print(any value);
Run Code Online (Sandbox Code Playgroud)

我可以像这样专注它让我们说int:

template<> print<int>(int value)
{
    std::cout << value;
}
Run Code Online (Sandbox Code Playgroud)

但现在问题是,我希望它也可以使用矢量.由于矢量类是模板类,因此变得困难.

专门化这样的功能:

template<class any> print<vector<any> >(vector<any> value) {}
Run Code Online (Sandbox Code Playgroud)

将生成以下错误(MinGW g ++):

FILE: error: function template partial specialization 'print<vector<any> >' is not allowed
Run Code Online (Sandbox Code Playgroud)

请注意,功能打印只是一个示例.

我怎么解决这个问题?

Seb*_*ach 5

有一个通用的解决方法,其中函数模板只是将作业委托给类模板成员函数:

#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);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以使用简单的函数重载(如ecatmur和Vaughn Cato所建议的那样),请执行此操作.