13.5 Relaxed Matching of Template Template Parameters

Ru-Brd

13.5 Relaxed Matching of Template Template Parameters

A template used to substitute a template template parameter must match that parameter's list of template parameters exactly. This can sometimes have surprising consequences, as shown in the following example:

 #include <list>  // declares:   //  namespace std {  //  template <typename T,  //  typename Allocator = allocator<T> >  //  class list;  //  }  template<typename T1,           typename T2,           template<typename> class Container>  //  Container  expects templates with only one parameter  class Relation {    public:   private:      Container<T1> dom1;      Container<T2> dom2;  };  int main()  {      Relation<int, double, std::list> rel;  // ERROR:  std::list  has more than one template parameter    } 

This program is invalid because our template template parameter Container expects a template taking one parameter, whereas std::list has an allocator parameter in addition to its parameter that determines the element type.

However, because std::list has a default template argument for its allocator parameter, it would be possible to specify that Container matches std::list and that each instantiation of Container uses the default template argument of std::list (see Section 8.3.4 on page 112).

An argument in favor of the status quo (no match) is that the same rule applies to matching function types. However, in this case the default arguments cannot always be determined because the value of a function pointer usually isn't fixed until run time. In contrast, there are no "template pointers," and all the required information can be available at compile time.

Some C++ compilers already offer the relaxed matching rule as an extension. This issue is also related to the issue of typedef templates (discussed in the next section). Indeed, consider replacing the definition of main() in our previous example with:

 template <typename T>  typedef list<T> MyList;  int main()  {      Relation<int, double, MyList> rel;  } 

The typedef template introduces a new template that now exactly matches Container with respect to its parameter list. Whether this strengthens or weakens the case for a relaxed matching rule is, of course, arguable.

This issue has been brought up before the C++ standardization committee, which is currently not inclined to add the relaxed matching rule.

Ru-Brd


C++ Templates
C++ Templates: The Complete Guide
ISBN: 0201734842
EAN: 2147483647
Year: 2002
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net