11.6 Default Call Arguments

Ru-Brd

Default function call arguments can be specified in function templates just as they are in ordinary functions:

 template<typename T>  void init (T* loc, T const& val = T())  {      *loc = val;  } 

In fact, as this example shows, the default function call argument can depend on a template parameter. Such a dependent default argument is instantiated only if no explicit argument is provided ”a principle that makes the following example valid:

 class S {    public:      S(int, int);  };  S s(0, 0);  int main()  {     init(&s, S(7, 42));  //  T()  is invalid for  T=S  , but the default   // call argument  T()  needs no instantiation   // because an explicit argument is given  } 

Even when a default call argument is not dependent, it cannot be used to deduce template arguments. This means that the following is invalid C++:

 template<typename T>  void f (T x = 42)  {  }  int main()  {      f<int>();  // OK:  T = int      f();  // ERROR: cannot deduce  T  from default call argument  } 
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