模板化 类 中的模板化函数

Templated functions in templated classes

我正在构建一个使用表达式模板的库,我在其中大量使用 classes 中的模板化函数。我所有的代码都是 运行,最近我决定将主要的 class 模板化,以允许在不同类型的数据上使用它。但是,我不能再专门化我的功能。我该如何解决这个问题?我附上了一个显示问题的小测试程序。

我之前的 Animal class 没有模板化,然后这段代码工作正常。

#include<iostream>
#include<vector>

// Example templated class with templated function
template<class T>
class Animals
{
  public:
    template<class X>
    void printFood(const X& x) const { std::cout << "We eat " << x << "!" << std::endl; }

  private:
    std::vector<T> animals;
};

// How do I specialize?
template<class T> template<>
void Animals<T>::printFood(const unsigned int& x) const { std::cout << "We don't want to eat " << x << "!" << std::endl; }

// Main loop;
int main()
{
  Animals<double> doubleAnimals;

  const int banana = 42;
  doubleAnimals.printFood(banana);

  const unsigned int apple = 666;
  doubleAnimals.printFood(apple);

  return 0;
}

您不能部分特化非特化模板的模板成员 class。这与禁止模板函数的部分特化是一致的(将模板 class 视为成员函数的第一个参数)。改用重载:

template<class T>
class Animals
{
public:
    template<class X>
    void printFood(const X& x) const { std::cout << "We eat " << x << "!" << std::endl; }

    void printFood(const unsigned int& x) const { std::cout << "We don't want to eat " << x << "!" << std::endl; }

private:
    std::vector<T> animals;
};

这根本不可能

[temp.expl.spec]

16 In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

你应该先专攻你的class。然后特化函数:

template<> template<>
void Animals<double>::printFood(const unsigned int& x) const { std::cout << "We don't want to eat " << x << "!" << std::endl; }