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.
Move the function out of
class Strategy<T>
.It seems to me like what you want to implement is a Policy-Based Design. I'm not sure what
Model
andStrategy
do exactly, but it seems likeModel
is the root class, andStrategy
is 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
Strategy
class to do your magic. By letting the users define their ownStrategy
class, you give them the opportunity to define their own "magic". You need to apply rules on what method theStrategy
class will provide at a minimum, so that you can call those methods inModel
.For example, suppose
Model
is 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 renameModel
toauto_resource
andStrategy
will becomerelease_policy
and will be responsible for releasing whatever resource was assigned to it. In that case, you might have:Which you could use for
std::string
pointers like this:...and when
my_str
falls off the stack, therelease
method will automatically be called.Later you want to add a new policy for releasing Windows mutex
HANDLE
s: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_SECTION
s, and another forSOCKET
s:For more on policy-based design, see Modern C++ Design.
...