user62089
user62089

Reputation: 561

C++ template class, changing behaviour of class method based on typename

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?

Upvotes: 1

Views: 858

Answers (1)

DimChtz
DimChtz

Reputation: 4343

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.

Upvotes: 5

Related Questions