1

I have a template class whose method I am trying to specialize based on the typename in class. A skeleton of the code is as follows:

template <typename C> class Instance {
  protected:
    C data;
  public:
    void populateData();
    /* want to change the behavior of populateData() depending on C */
};

How do I achieve the above stated goal?

user62089
  • 531
  • 1
  • 9
  • 21
  • https://en.cppreference.com/w/cpp/language/template_specialization#Members_of_specializations – NathanOliver Jun 19 '18 at 15:50
  • 3
    Possible duplicate of [explicit specialization of template class member function](https://stackoverflow.com/questions/5512910/explicit-specialization-of-template-class-member-function) – AVH Jun 19 '18 at 15:51
  • In reality I have multiple class members and functions that retain the same implementation - do I have to reimplement all those functions that do not change too. This is one of the source of my confusion when I try to specialize the class itself. – user62089 Jun 19 '18 at 15:51

1 Answers1

5

I think this is what you want:

template <typename C> class Instance {
  protected:
    C data;
  public:
    void populateData();
    /* want to change the behavior of populateData() depending on C */
};

template<>
void Instance<int>::populateData() {
    // Do something when C is int
}

You can specialize the function for any type you want.

DimChtz
  • 4,043
  • 2
  • 21
  • 39
  • 1
    Note: Only works with fully specialization: `template void Instance>::populateData()` won't be possible. – Jarod42 Jun 19 '18 at 17:36