使用模板类的函数模板专业化[重复]

2023-11-29

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

我无法在任何地方找到我的问题的解决方案,因为如果我使用我提出的关键字进行搜索,将为我提供适合不同问题的解决方案。我知道这一定是以前问过的,只是找不到解决方案。

假设我有一个函数模板:

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

请注意,函数 print 只是一个示例。

我该如何解决这个问题?


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

#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 的建议),请这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用模板类的函数模板专业化[重复] 的相关文章

随机推荐