Home > Articles > Programming > C/C++

This chapter is from the book

Solution

Generic Quality

  1. What qualities are desirable in designing and writing generic facilities? Explain.

Generic code should above all be usable. That doesn't mean it has to include all options up to and including the kitchen sink. What it does mean is that generic code ought to make a reasonable and balanced effort to avoid at least three things:

  1. Avoid undue type restrictions. For example, are you writing a generic container? Then it's perfectly reasonable to require that the contained type have, say, a copy constructor and a nonthrowing destructor. But what about a default constructor or an assignment operator? Many useful types that users might want to put into our container don't have a default constructor, and if our container uses it, then we've eliminated such a type from being used with our container. That's not very generic. (For a complete example, see Item 11 of Exceptional C++ [Sutter00].)

  2. Avoid undue functional restrictions. If you're writing a facility that does X and Y, what if some user wants to do Z, and Z isn't so much different from Y? Sometimes you'll want to make your facility flexible enough to support Z; sometimes you won't. Part of good generic design is choosing the ways and means by which your facility can be customized or extended. That this is important in generic design should hardly be a surprise, though, because the same principle applies to object-oriented class design.

Policy-based design is one of several important techniques that allow "pluggable" behavior with generic code. For examples of policy-based design, see any of several chapters in [Alexandrescu01]; the SmartPtr and Singleton chapters are a good place to start.

This leads to a related issue:

  1. Avoid unduly monolithic designs. This important issue doesn't arise as directly in our style example under consideration below, and it deserves some dedicated consideration in its own right, hence it gets not only its own Item, but its own concluding miniseries of Items: see Items 37 through 40.

In these three points, you'll note the recurring word "undue." That means just what it says: Good judgment is needed when deciding where to draw the line between failing to be sufficiently generic (the "I'm sure nobody would want to use it with anything but char" syndrome) on the one hand and overengineering (the "what if someday someone wants to use this toaster-oven LED display routine to control the booster cutoff on an interplanetary spacecraft?" misguided fantasy) on the other.

Dissecting Generic Callbacks

  1. The following code presents an interesting and genuinely useful idiom for wrapping callback functions. For a more detailed explanation, see the original article. [Kalev01]

Here again is the code:

template < class T, void (T::*F)() >
   class callback
   {
   public:
   callback(T& t) : object(t) {}       // assign actual object to T
   void execute() { (object.*F)(); }   // launch callback function
   
   private:
   T& object;
   };
   

Now, really, how many ways are there to go wrong in a simple class with just two one-liner member functions? Well, as it turns out, its extreme simplicity is part of the problem. This class template doesn't need to be heavyweight, not at all, but it could stand to be a little less lightweight.

Improving Style

  • Critique this code and identify:

    1. Stylistic choices that could be improved to make the design better for more idiomatic C++ usage.

How many did you spot? Here's what I came up with:

  1. The constructor should be explicit. The author probably didn't mean to provide an implicit conversion from T to callback<T>. Well-behaved classes avoid creating the potential for such problems for their users. So what we really want is more like this:

    explicit callback(T& t) : object(t) {} // assign actual object to T
             

While we're already looking at this particular line, there's another stylistic issue that's not about the design per se but about the description:

Guideline

Prefer making constructors explicit unless you really intend to enable type conversions.

(Nit) The comment is wrong. The word "assign" in the comment is incorrect and so somewhat misleading. More correctly, in the constructor, we're "binding" a T object to the reference and by extension to the callback object. Also, after many rereadings I'm still not sure what the "to T" part means. So better still would be "bind actual object."

explicit callback(T& t) : object(t) {} // bind actual object
   

But then, all that comment is saying is what the code already says, which is faintly ridiculous and a stellar example of a useless comment, so best of all would be:

explicit callback(T& t) : object(t) {}
  1. The execute function should be const. The execute function isn't doing anything to the callback<T> object's state, after all! This is a "back to basics" issue: Const correctness might be an oldie, but it's a goodie. The value of const correctness has been known in C and C++ since at least the early 1980s, and that value didn't just evaporate when we clicked over to the new millennium and started writing lots of templates.

void execute() const { (object.*F)(); }       // launch callback function
   

Guideline

Be const correct.

While we're already beating on the poor execute function, there's an arguably more serious idiomatic problem:

  1. (Idiom) And the execute function should be spelled operator(). In C++, it's idiomatic to use the function-call operator for executing a function-style operation. Indeed, then the comment, already somewhat redundant, becomes completely so and can be removed without harm because now our code is already idiomatically commenting itself. To wit:

    void operator()() const { (object.*F)(); } // launch callback function
             

"But," you might be wondering, "if we provide the function-call operator, isn't this some kind of function object?" That's an excellent point, which leads us to observe that, as a function object, maybe callback instances ought to be adaptable too.

Guideline

Provide operator() for idiomatic function objects rather than providing a named execute function.

Pitfall: (Idiom) Should this callback be derived from std::unary_function? See Item 36 in [Meyers01] for a more detailed discussion about adaptability and why it's a Good Thing in general. Alas, here, there are two excellent reasons why callback should not be derived from std::unary_function, at least not yet:

  • 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 might 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 matters only 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.)

Correcting Mechanical Errors and Limitations

  1. Mechanical limitations that restrict the usefulness of the facility.

  1. 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) {}      // bind  actual object
             void operator()() const { (object.*f)(); }             // launch callback function
             
             private:
             T& object;
             Func f;
             };
             

Now the function to be used can vary at run-time, and it would be simple to add a member function that allowed the user to change the function that an existing call-back 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.

  1. Enable 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, such as a vector or a list? Currently that's not possible, because call-back 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 what-ever 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) {}      // bind actual object
   void operator()() const { (object->*f)(); }             // launch callback function
   
   private:
   T* object;
   Func f;
   };
   

Now it's possible to have, for example, a list< callback< Widget, &Widget::Some-Func > >.

Guideline

Prefer to make your objects compatible with containers. In particular, to be put into a standard container, an object must be assignable.

"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:

  1. Enable polymorphism: Provide a common base class for callback types. If we want to let users have a list<callbackbase*> (or, better, a list< shared_ptr<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) {}       // bind actual object
             void operator()() const { (object->*f)(); }              // launch callback function
             
             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< shared_ptr<callback> > would be even better; see [Sutter02b].

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 actually manifests only when you use the base interface. Code that doesn't need the base interface doesn't pay for it.

Guideline

Consider enabling polymorphism so that different instantiations of your class template can be used interchangeably, if that makes sense for your class template. If it does, do it by providing a common base class shared by all instantiations of the class template.

  1. (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 std::make_pair. The missing make_callback helper should be a function template, because that's the only kind of template for which a 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);
}
  1. (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) ()!"

Guideline

Avoid limiting your template; avoid hardcoding for specific types or for less general types.

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 you're having trouble with insomnia, see books and articles like [Alexandrescu01] 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.

Summary

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);
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020