简体   繁体   中英

Templated functions in templated classes

I am constructing a library that makes use of expression templates, where I make heavily use of templated functions in classes. All my code is running and recently I decided to make the main class templated to allow for using it on data of different kinds. However, I can no longer specialize my functions. How do I solve this? I have attached a small test program that shows the problem.

My previous Animal class was not templated and then this code works fine.

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

This simply isn't possible

[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.

You should specialize your class first. Then specialize function:

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

You can't partially specialize template members of non-specialized template class. This is consistent with prohibiting partial specialization of template functions (think of template class as the member function's first parameter). Use overloading instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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