1

I've seen solutions to this problem that suggest using

if( dynamic_cast<DerviedType1*>( base ) ){
    // Do something
}
else if( dynamic_cast<DerviedType2*>( base ) ){
    // Do something else
}
else if( dynamic_cast<DerviedType3*>( base ) ){
   // Do another thing
}
// and so on

While functional, this solution is far from elegant, and I was hoping that there was a single-line solution, along the lines of decltype or typeid, neither of which help me here.

My specific problem is as follows. I have a function that will take a pointer to an instance of the base class as an argument. This function will then call a template function within that takes the derived type as its parameter. E.g.

void myFunc( Base *base )
{
    myTemplateFunc<Derived>();
}

I would like to keep my code simple, without a laundry list of if statements, but I'm not sure how to go about it. It should be noted that the Base object itself will not be passed into the template function, only it's type.

For reference, I'm looking for something along the lines of

void myFunc( Base *base )
{
    myTemplateFunc<decltype(base)>();
}

but this will only return the Base type, which doesn't help me here.

4

2 回答 2

7

The other way is multiple dispatching

class Base
{
   virtual void dispatch () = 0;
};

template <class T>
class BaseTpl : public Base
{
public:
  void dispatch () {myTemplateFunc<T> ();}
};

and then

class DerviedType1 : public BaseTpl <DerviedType1>
{
};

and actual ussage

void myFunc( Base *base )
{
    base->dispatch ();
}
于 2012-10-31T13:47:16.633 回答
5

How about

struct Base
{
   virtual void execute() = 0;
}

struct Derived : Base
{
   virtual void execute()
   {
      myTemplateFunc<Derived>();
   }
}

and just call it as

void myFunc( Base *base )
{
    base->execute();
}

which will dispatch to the correct method.

于 2012-10-31T13:45:38.093 回答