功能模板专业化具有模板类

Function template specialization with a template class

本文关键字:专业化 功能      更新时间:2023-10-16

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

我找不到解决问题的解决方案,因为如果我搜索我想出的关键字,就会为我提供适合不同问题的解决方案。我知道之前必须提出过这一点,只是找不到解决方案。

假设我有一个函数模板:

template<class any> print(any value);

我可以这样对此进行专业化,例如 int

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

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

专门为这样的功能:

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

将生成以下错误(mingw g ):

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

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

如何解决此问题?

有一个一般的解决方法,其中功能模板只是将作业委派给类模板成员函数:

#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);
}

但是,如果您可以通过简单的功能过载(如Ecatmur和Vaughn Cato的建议),请这样做。

不要尝试专业化功能模板。改用过载

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

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

功能模板不允许部分专业化,因为它会导致一定的规则违规。您通常只能使用过载:

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