Re: Reference to a pointer of another type
Here's another solution based on a template getter method,
Code:
class Worker {
};
class Manager
{
public:
virtual void some_method() = 0;
protected:
Manager(Worker* p) : pWorker(p) {}
template<typename DERIVED>
DERIVED* getWorker() {
return static_cast<DERIVED*>(pWorker);
}
private:
Worker* pWorker;
};
class Worker1 : public Worker {
public:
void some_worker1_specific_method() {
std::cout << "hello\n";
}
};
class Manager1 : public Manager
{
public:
Manager1() : Manager(new Worker1) {}
private:
void some_method()
{
getWorker<Worker1>()->some_worker1_specific_method(); //cool, this works!
}
};
The advantage is that the pWorker pointer is held once only like in the virtual getter approach. The virtual getter approach is safer but this is medium safe and since the getWorker function will be inlined there's no performance penalty.
Note that in this case Manager must assume ownership of the pWorker object and make sure it gets destructed.