basic_string <char>如何只提供模板参数“char”,而basic_string是一个参数模板

时间:2016-08-29 01:56:29

标签: c++ templates stl

我定义了一个这样的字符串对象:

string test;

我想知道stl如何实现字符串,我发现字符串是basic_string,如下所示:

typedef basic_string<char>    string;

但basic_string是这样的模板:

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;
  ......
}

我只想知道basic_string只提供一个模板参数“char”,而basic_string实际上是一个参数模板

template<typename _CharT, typename _Traits, typename _Alloc>

1 个答案:

答案 0 :(得分:2)

std::basic_string具有默认模板参数。根据标准,声明是:

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