Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how the default values of template parameters are declared

Tags:

c++

templates

In the std::basic_string documentation found at http://en.cppreference.com/w/cpp/string/basic_string, the basic_string class is declared as follows.

template<
    class CharT,
    class Traits = std::char_traits<CharT>,
    class Allocator = std::allocator<CharT>
> class basic_string;

However, in both GCC and Visual Studio the default values for the Traits and Allocator template parameters are not specified in the class declaration.

The following is from basic_string.h from GCC 4.9.2.

template<
    typename _CharT,
    typename _Traits,
    typename _Alloc
> class basic_string

Note the lack of default values for the _Traits and _Alloc template parameters.

What am I missing?

like image 524
Ben Key Avatar asked May 14 '15 09:05

Ben Key


People also ask

Can template parameters have default values?

Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.

How default arguments are used in template?

If one template parameter has a default argument, then all template parameters following it must also have default arguments. For example, the compiler will not allow the following: template<class T = char, class U, class V = int> class X { };

How do you declare a template?

To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.

What are template parameters?

In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.


1 Answers

These classes are usually declared in a million places1. Only one of those declarations will carry the default arguments, because it's an error otherwise.

For basic_string, in libstdc++, the default arguments are found in a forward declaration in bits/stringfwd.h (which is included by <string>, among other things):

  template<typename _CharT, typename _Traits = char_traits<_CharT>,
           typename _Alloc = allocator<_CharT> >
    class basic_string;

1 Not to be taken literally.

like image 90
T.C. Avatar answered Oct 06 '22 00:10

T.C.