I have structure for storing callback function like this:
template<class T>
struct CommandGlobal : CommandBase
{
typedef boost::function<T ()> Command;
Command comm;
virtual T Execute() const
{
if(comm)
return comm();
return NULL;
}
};
Seems like it should work fine except when T is void because the Execute function wants to return a value..
What is the best solution to this problem?
Thanks!
This answer is based off this fun-fact: In a function returning
void, you can return any expression of which the type is void.So the simple solution is:
When
T = void, the last return statement is equivalent toreturn;.However, I feel this is bad design. Is
NULLmeaningful for everyT? I don’t think so. I would throw an exception:However, this is done automatically by Boost, so your code becomes the much cleaner:
You could then add additional functionality, such as:
So the user can check if it can be called prior to calling it. Of course at this point, unless your class has additional functionality you’ve left out for the sake of the question, I see no reason not to just use
boost::functionin the first place.