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