繁体   English   中英

模板化类中的模板化函数

[英]Templated functions in templated classes

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

我之前的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;
}

这根本不可能

[temp.expl.spec]

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM