I want to breakup a class so that its decoupled from the logic of performing certain task so that users can write new strategies as they wish to without interfering with the central model. So, I want to use templated strategy class but without having to have the user of the strategy to be templatised:
class Model {
...
boost::shared_ptr< Strategy < T > > m_pStrategy;
...
public:
template < typename T >
void DoSomething() { m_pStrategy < T > ::DoSomething(); }
};
I would like the DoSomething function to not be templated. Is there any other way I can achieve what I want to do here?
thanks.
It seems to me like what you want to implement is a Policy-Based Design. I’m not sure what
ModelandStrategydo exactly, but it seems likeModelis the root class, andStrategyis the Policy class, which users would want to provide in some cases to perform special handling. It also seems like the only reason you keep a pointer to theStrategy<T>object around is so that you can call functions on it.In this case, you can design your class like this:
You call methods on the
Strategyclass to do your magic. By letting the users define their ownStrategyclass, you give them the opportunity to define their own “magic”. You need to apply rules on what method theStrategyclass will provide at a minimum, so that you can call those methods inModel.For example, suppose
Modelis actually some kind of resource manager, capable of being a simple smart pointer, or something else like a resource manager for a Windows Critical Section. Let’s renameModeltoauto_resourceandStrategywill becomerelease_policyand will be responsible for releasing whatever resource was assigned to it. In that case, you might have:Which you could use for
std::stringpointers like this:…and when
my_strfalls off the stack, thereleasemethod will automatically be called.Later you want to add a new policy for releasing Windows mutex
HANDLEs:You can use this thusly:
Of course, in order to flesh all this out you need to add functionality for assigning, copying, releasing etc the resources. Here is a complete working example that puts everything together. I’ve provided 2 sets of policies, one for Windows
CRITICAL_SECTIONs, and another forSOCKETs:For more on policy-based design, see Modern C++ Design.
…