cong cong - 3 months ago 12
C++ Question

how basic_string<char>,which only offered a template parameter "char", works while basic_string is a there-parameter template

I define a string object like this:

string test;


I want to know how stl implement string,and I found that string is basic_string,like this:

typedef basic_string<char> string;


but basic_string is a template like this:

template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type;

// Types:
public:
typedef _Traits traits_type;
typedef typename _Traits::char_type value_type;
typedef _Alloc allocator_type;
typedef typename _CharT_alloc_type::size_type size_type;
typedef typename _CharT_alloc_type::difference_type difference_type;
typedef typename _CharT_alloc_type::reference reference;
typedef typename _CharT_alloc_type::const_reference const_reference;
typedef typename _CharT_alloc_type::pointer pointer;
typedef typename _CharT_alloc_type::const_pointer const_pointer;
typedef __gnu_cxx::__normal_iterator<pointer, basic_string> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, basic_string>
const_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
......
}


I just want to kown that how basic_string,which offered only one template parameter "char",works while basic_string is literally a there-parameter template

template<typename _CharT, typename _Traits, typename _Alloc>

Answer

std::basic_string has default template arguments. According to the standard, the declaration is:

template<class charT, class traits = char_traits<charT>,
  class Allocator = allocator<charT> >
class basic_string