【问题标题】:Function template specialization with a template class [duplicate]具有模板类的函数模板特化[重复]
【发布时间】:2012-11-08 14:46:27
【问题描述】:

可能重复:
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

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

我该如何解决这个问题?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 我最终在使用重载时遇到了很多问题,这对我有用,谢谢!
  • 它是否必须在 same 文件中专门化?现在遇到很多错误..
  • 不一定是这样,但通常会更好。将专业化分布在不能保证包含在一起的不同文件上,可能会给您带来一些痛苦,尤其是当您对模板没有太多经验时。
  • 感谢您的回复。什么时候必须包含模板专业化?在定义函数中使用它时,还是在定义 int main() {...} 之前? 编辑: 为什么我可以在其他单元和类模板中专门化函数模板而不是!?
【解决方案2】:

不要试图专门化函数模板。改用重载

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多