Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function depending on template type in C++?

Tags:

c++

oop

class

model

I have the following hierarchy of class:

class Boy : Child
class Girl : Child

template<class T>
class Parent
{
    vector<T> children;
}


class AnnaBoys: public Parent<Boy>
{
 void ProcessChild() { do things specific to Anna boys };
};

class AnnaGirls: public Parent<Girl>
{
 void ProcessChild() { do things specific to Anna girls};
};

The two ProcessChild() function here are doing unrelated things, not "templetable" in the way add<T> could be.

I'm looking to avoid having to create two Anna class and just do this instead:

template<class T>
class Anna: public Parent<T>
    {
     void ProcessChild() 
     { 
        if(T is Boys)
         ProcessBoys();
        else
         ProcessGirls();
      };
    };

Is there any clean way to do this without doing a dynamic_cast at runtime ?

Thanks.

like image 866
user2164703 Avatar asked Dec 20 '22 06:12

user2164703


1 Answers

You can specialize individual member functions without specifying the whole class. In this case:

Header:

template<typename T>
class Anna : Parent<T> {
public:
  void ProcessChild() {
    // default implementation (if desired)
  }
};

template<> void Anna<Boy>::ProcessChild();
template<> void Anna<Girl>::ProcessChild();

Source file:

template<> void Anna<Boy>::ProcessChild() {
  // implementation for boys
}

template<> void Anna<Girl>::ProcessChild() {
  // implementation for girls
}

It is possible to have the specialized member functions in the header by declaring them inline, if you want to keep things header-only:

template<typename T>
class Anna : Parent<T> {
public:
  void ProcessChild() {
    // default implementation (if desired)
  }
};

template<> inline void Anna<Boy>::ProcessChild() {
  // implementation for boys
}

template<> inline void Anna<Girl>::ProcessChild() {
  // implementation for girls
}

Thanks to @Deduplicator for spotting that.

like image 174
Wintermute Avatar answered Jan 06 '23 20:01

Wintermute