I have the following piece of code which doesn’t compile when I try to instance something like CommandGlobal<int> because it tries to override virtual void Execute() const =0; with a function which returns int. It gives a non-covariance error.
class CommandBase
{
public:
virtual void Execute() const =0;
};
template<class T>
struct CommandGlobal : CommandBase
{
typedef boost::function<T ()> Command;
Command comm;
virtual T Execute() const
{
return comm();
}
};
template<class T>
struct CommandMemberFunction : CommandBase
{
typedef boost::function<T (int, std::string)> Command;
Command comm;
int entityid;
std::string mfid;
virtual T Execute() const
{
return comm(entityid, mfid);
}
};
I have asked this question before and recieved an answer which I couldn’t figure out exactly how to implement. The answer given is as follows:
Quick & dirty answer: pass to Execute a reference to the result type as a void*, and make Execute private. Then wrap Execute in a non-virtual wrapper which returns T by value and does the cast.
Could anyone clarify this answer with a bit of code. I would appreciate this greatly.
Thanks all!
I think he meant something like (a little bit simplified):
Although it's quite error-prone. I'd suggest that you redesign your base interface to have a common interface for T so your Execute() doesn't return void but instead IMyClass or something similar.