Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 23.  Template Constructors


23.5. Argument Targeting

It's pretty disappointing stuff really, and something we can all hope the next standardization will address explicitly. In my opinion, compilers should be required to work correctly with all permutations (const/non-const, volatile/non-volatile, by-value/reference/pointer), and to select the most specialized as appropriate, rather than complaining about ambiguities. A former colleague once expressed disdain that compilers cannot work out what is needed on a case-by-case basis, but obliging compilers to look "through" a template to see how an argument is used within a given instantiation would be asking too much, I think.

The prosaic and incomplete solution to this is a targeted approach. Many bolt-ins and other deriving templates generally have a predictable subset of types that they must work with. In such cases, one can target the template constructors accordingly. For example, the veneer template sequence_container_veneer (see Chapter 21; included on the CD) designed to be parameterized by the standard library sequence containers—list, vector and deque[6]—would only need to provide for the following constructors:

[6] I'm not counting basic_string, although it too is a sequence container.



// C = container; V = value type; A = allocator


explicit C(A const &al = A());


explicit C(size_type n, V const &v = V(), A const &al = A());


         C(C::const_iterator first, C::const_iterator last


                                  , A const &al = A());



With types that really do have to be very widely applicable, you can resign yourself to your fate and wrap all the permutations in a macro, comforting yourself that it's not your fault.


      Previous section   Next section