13.15 Initializer Deduction

Ru-Brd

13.15 Initializer Deduction

It is often said that "programmers are lazy," and sometimes this refers to our desire to keep programmatic notation compact. Consider, in that respect, the following declaration:

 std::map<std::string, std::list<int> >* dict  = new std::map<std::string, std::list<int> >; 

This is verbose, and in practice we would (and most likely should) introduce a typedef synonym for the type. However, there is something redundant in this declaration: We specify the type of dict , but it is also implicit in the type of its initializer. Wouldn't it be considerably more elegant to be able to write an equivalent declaration with only one type specification? For example:

 dcl dict = new std::map<std::string, std::list<int> >; 

In this last declaration, the type of a variable is deduced from the type of the initializer. A keyword ( dcl in the example, but var , let , and even auto have been proposed as alternatives) is needed to make the declaration distinguishable from an ordinary assignment.

So far, this isn't a template-only issue. In fact, it appears such a construct was accepted by a very early version of the Cfront compiler (in 1982, before templates came on the scene). However, it is the verbosity of many template-based types that increases the demand for this feature.

One could also imagine partial deduction in which only the arguments of a template must be deduced:

 std::list<> index = create_index(); 

Another variant of this is to deduce the template arguments from the constructor arguments. For example:

 template <typename T>  class Complex {    public:      Complex(T const& re, T const& im);   };  Complex<> z(1.0, 3.0);  // deduces  T = double 

Precise specifications for this kind of deduction are made more complicated by the possibility of overloaded constructors, including constructor templates. Suppose, for example, that our Complex template contains a constructor template in addition to a normal copy constructor:

 template <typename T>  class Complex {    public:      Complex(Complex<T> const&);      template <typename T2> Complex(Complex<T2> const&);   };  Complex<double> j(0.0, 1.0);  Complex<> z = j;  // Which constructor was intended?  

In the latter initialization, it is probable that the regular copy constructor was intended; hence z should have the same type as j . However, making it an implicit rule to ignore constructor templates may be overly bold.

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