2

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

我以前的Animal课程没有模板化,然后这段代码可以正常工作。

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

3 回答 3

7

这根本不可能

[temp.expl.spec]

16 在类模板的成员或出现在命名空间范围内的成员模板的显式特化声明中,成员模板和它的一些封闭类模板可能保持未特化,除非声明不应显式特化类成员模板,如果它的封闭类模板也没有明确专门化。

于 2015-01-27T10:18:49.213 回答
2

你应该首先专业化你的课程。然后专门化功能:

template<> template<>
void Animals<double>::printFood(const unsigned int& x) const { std::cout << "We don't want to eat " << x << "!" << std::endl; }
于 2015-01-27T10:20:05.403 回答
0

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

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;
};
于 2015-01-27T10:18:48.597 回答