|
Style Case Study #2: Generic Callbacks |
It's not a unary function. It takes no parameter, and unary functions take a parameter. (No, "void" doesn't count.) | |
Deriving from std::unary_function isn't going to be extensible anyway. Later on, we're going to see that callback perhaps ought to work with other kinds of function signatures too, and depending on the number of parameters involved, there may well be no standard base class to derive from. For example, if we supported callback functions with three parameters, we have no std::ternary_function to derive from. |
Deriving from std::unary_function or std::binary_function is a convenient way to give callback a handful of important typedefs that binders and similar facilities often rely upon, but it only matters if you're going to use the function objects with those facilities. Because of the nature of these callbacks and how they're intended to be used, it's unlikely that this will be needed. (If in the future it turns out that they ought to be usable this way for the common one- and two-parameter cases, then the one- and two-parameter versions we'll mention later can be derived from std::unary_function and std::binary_function, respectively.)
b) Mechanical limitations that restrict the usefulness of the facility.
Consider making the callback function a normal parameter, not a template parameter.
Non-type template parameters are rare in part because there's rarely much benefit in so strictly fixing a type at compile time. That is, we could instead have:
template < class T >
class callback
{
public:
typedef void (T::*Func)();
callback( T& t, Func func ) : object(t), f(func) { }
void operator()() { (object.*f)(); }
private:
T& object;
Func f;
};
Now the function to be used can vary at runtime, and it would be simple to add a member function that allowed the user to change the function that an existing callback object was bound to, something not possible in previous versions of the code.
Guideline:
It's usually a good idea to prefer making non-type parameters into normal function parameters, unless they really need to be template parameters.
Containerization
If a program wants to keep one callback object for later use, it's likely to want to keep more of them. What if it wants to put the callback objects into a container, like a vector or a list? Currently that's not possible, because callback objects aren't assignable -- they don't support operator=(). Why not? Because they contain a reference, and once that reference is bound during construction it can never be rebound to something else.
Pointers, however, have no such compunction, and are quite happy to point at whatever you'd ask them to. In this case it's perfectly safe for callback instead to store a pointer, not a reference, to the object it's to be called on, and then to use the default compiler-generated copy constructor and copy assignment operator:
template < class T >
class callback
{
public:
typedef void (T::*Func)();
callback( T& t, Func func ) : object(&t), f(func) { }
void operator()() { (object->*f)(); }
private:
T* object;
Func f;
};
Now it's possible to have, for example, a list< callback< Widget, &Widget::SomeFunc > >.
"But wait," you might wonder at this point, "if I could have that kind of a list, why couldn't I have a list of arbitrary kinds of callbacks of various types, so that I can remember them all, and go execute them all when I want to?" Indeed, you can, if you add a base class:
Provide a common base class for callback types.
If we want to let users have a list<callbackbase*>, we can do it by providing just such a base class, which by default happens to do nothing in its operator()():
class callbackbase
{
public:
virtual void operator()() const { };
virtual ~callbackbase() = 0;
};
callbackbase::~callbackbase() { }
template < class T >
class callback : public callbackbase
{
public:
typedef void (T::*Func)();
callback( T& t, Func func ) : object(&t), f(func) { }
void operator()() const { (object->*f)(); }
private:
T* object;
Func f;
};
Now anyone who wants to can keep a list<callbackbase*> and polymorphically invoke operator()() on its elements. Of course, a list<boost::shared_ptr<callback> > would be even better.
Note that adding a base class is a tradeoff, but only a small one: We've added the overhead of a second indirection, namely a virtual function call, when the callback is triggered through the base interface. But that overhead only actually manifests when you use the base interface. Code that doesn't need the base interface doesn't pay for it.
(Idiom, Tradeoff) There could be a helper make_callback function to aid in type deduction.
After a while, users may get tired of explicitly specifying template parameters for temporary objects:
list< callback< Widget > > l;
l.push_back( callback<Widget>( w, &Widget::SomeFunc ) );
Why write Widget twice? Doesn't the compiler know? Well, no, it doesn't, but we can help it to know. in contexts where only a temporary object like this is needed. Instead, we could provide a helper so that they need only type:
list< callback< Widget > > l;
l.push_back( make_callback( w, &Widget::SomeFunc ) );
This make_callback works just like the standard make_pair(). The missing make_callback() helper should be a function template, because that's the only kind of template for which compiler can deduce types. Here's what the helper looks like:
template<typename T >
callback<T> make_callback( T& t, void (T::*f) () )
{
return callback<T>( t, f );
}
(Tradeoff) Add support for other callback signatures.
I've left the biggest job for last. As the Bard might have put it, "There are more function signatures in heaven and earth, Horatio, than are dreamt of in your void (T::*F) ()!"
If enforcing that signature for callback functions is sufficient, then by all means stop right there. There's no sense in complicating a design if we don't need to -- for complicate it we will, if we want to allow for more function signatures!
I won't write out all the code, because it's significantly tedious. (If you really want to see code this repetitive, or are having trouble with insomnia, see books and articles like [3] for similar examples.) What I will do is briefly sketch the main things you'd have to support, and how you'd have to support them:
First, what about const member functions? The easiest way to deal with this one is to provide a parallel callback that uses the const signature type, and in that version remember to take and hold the T by reference or pointer to const.
Second, what about non-void return types? The simplest way to allow the return type to vary is by adding another template parameter.
Third, what about callback functions that take parameters? Again, add template parameters, remember to add parallel function parameters to operator()(), and stir well. Remember to add a new template to handle each potential number of callback arguments.
Alas, the code explodes, and you have to do things like set artificial limits on the number of function parameters that callback supports. Perhaps in a future C++0x language we'll have features like template "varargs" that will help to deal with this, but not today.
Putting it all together, and making some purely stylistic adjustments like using "typename" consistently and naming conventions and whitespace conventions that I happen to like better, here's what we get:
class CallbackBase
{
public:
virtual void operator()() const { };
virtual ~CallbackBase() = 0;
};
CallbackBase::~CallbackBase() { }
template<typename T>
class Callback : public CallbackBase
{
public:
typedef void (T::*F)();
Callback( T& t, F f ) : t_(&t), f_(f) { }
void operator()() const { (t_->*f_)(); }
private:
T* t_;
F f_;
};
template<typename T>
Callback<T> make_callback( T& t, void (T::*f) () )
{
return Callback<T>( t, f );
}
[1] D. Kalev. "Designing a Generic Callback Dispatcher" (DevX).
[2] H. Sutter, Exceptional C++ (Addison-Wesley, 2000).
[3] A. Alexandrescu. Modern C++ Design (Addison-Wesley, 2001).
[4] S. Meyers. Effective STL (Addison-Wesley, 2001).
Copyright © 2009 Herb Sutter |