Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Best To Implement A Templated Class with Types That Depend On Each Other

Tags:

c++

c++11

As a simplified example, if I have the classes

template <class T, class U> class ProcessEvent
{
  public:
    ProcessEvent(T* t) : var1(t) { var2 = new U; }
    Process() { var2->Process(var1); }
  private:
    T* var1;
    U* var2;
};

class Foo 
{
  /*data*/
};

class FooProcessor 
{
  void Process(Foo* foo) {/*functionality*/}
};

class Bar
{
  /*data*/
};

class BarProcessor 
{
  void Process(Bar* bar) {/*functionality*/}
};

So the class ProcessEvent can take have two different sets of template types,

ProcessEvent<Foo, FooProcessor>
ProcessEvent<Bar, BarProcessor> 

However, the second template type FooProcessor and BarProcessor are directly implied by the first template type and are implementation details the user doesn't care about. My goal is to have the same functionality as above, but have ProcessEvent take only a single template parameter, Foo or Bar. Other than through specialization of ProcessEvent, can this be done?

like image 468
user334066 Avatar asked Dec 22 '22 02:12

user334066


1 Answers

I'm going to assume that you simplified for clarity and are reallyusing smart pointers or at least properly managing the memory.

The easiest way to do this is with a typedef in the first class:

class Foo
{
    typedef FooProcessor Processor;
    // Stuff.
};

Then in your template get rid of U and use typename T::Processor instead.

like image 135
Mark B Avatar answered Dec 24 '22 01:12

Mark B