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

时间:2012-11-08 14:46:28

标签: c++ function templates specialization partial-specialization

  

可能重复:
  partial specialization of function template

我找不到任何解决方案来解决我的问题,因为如果我用我想出的关键字进行搜索会给我一些适合不同问题的解决方案。我明白以前一定要问这个问题,但是找不到解决办法。

假设我有一个功能模板:

template<class any> print(any value);

我可以像这样专门说一下int

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

但是现在问题是,我希望它也可以使用矢量。由于vector类是模板类,因此很难。

专业化这样的功能:

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

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

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

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

我该如何解决这个问题?

3 个答案:

答案 0 :(得分: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);
}

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

答案 1 :(得分:2)

不要尝试专门化功能模板。使用重载

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

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

答案 2 :(得分:1)

不允许使用函数模板部分特化,因为它会导致违反单定义规则。您通常只能使用重载:

template<class any> print(vector<any> value) {}
相关问题