2

I am writing a policy pattern class, which looks like:

template<typename Worker, typename Location, typename Behavior>
class Driver {
public:

    Location location;
    Behavior behavior;

    Worker* worker;

    Driver();

    void start();

};

in the cpp file, I have this:

template <typename Worker, typename Exchange, typename Behavior>
Driver<Worker, Exchange, Behavior>::Driver(){
    worker = new Worker();
};



template <typename Worker, typename Location, typename Behavior>
void Driver<Worker, Location, Behavior>::start(){
    ;
};


template class Driver<WorkerStruct1, LocationStruct1, BehaviorStruct1>;

here is the problem, I have quite a few of WorkerStruct and LocationStruct and BehaviorStruct. The very reason that I use policy pattern is to avoid the 'combination explosion'.

however, if I have to instantiate all the templates, I will have a big pile of instantiation lines at the bottom of the cpp file. Say, I have 7 for each of these 3 components, then I have 7 * 7 * 7 = 343 lines.

Is this how policy pattern suppose to work?

Some comments asked me why I instantiate the template. I don't know what went wrong, but if I don't instantiate, I get compilation error: "undefined reference to Driver<....>::Driver()"

user152503
  • 401
  • 2
  • 15
  • 1
    Why are you instantiating the templates? You don't need to if you define everything in the header file – NathanOliver Mar 05 '18 at 20:42
  • Ordinarily, the compiler takes care of instantiating templates. You don't have to instantiate them yourself unless you've done something peculiar. – Pete Becker Mar 05 '18 at 20:47
  • The "peculiar" thing Pete refers to is *not* defining the templates in a header: that's what is normally done unless there is a good reason to do things differently (e.g., using explicit instantiation with the IOStreams and locales library improves [used to improve? - it is a while since I measured the difference] compile times dramatically). – Dietmar Kühl Mar 05 '18 at 21:11
  • Do you define teplate classes methods in a separate .cpp file and try to squeeze them in a binary library? That is probably the only reason you could need expicit instantiations. – bipll Mar 05 '18 at 21:11
  • Hi all, this is not a library. I am not doing anything fancy. I have a main.cpp file. If I don't add the instantiation line, the program won't compile – user152503 Mar 05 '18 at 21:19
  • 1
    Which part of ["define your template in the header file"](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) do you find unclear? – Igor Tandetnik Mar 06 '18 at 00:03

0 Answers0