【问题标题】:how basic_string<char>,which only offered a template parameter "char", works while basic_string is a there-parameter template仅提供模板参数“char”的 basic_string<char> 如何工作,而 basic_string 是一个参数模板
【发布时间】:2016-08-29 01:56:29
【问题描述】:

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

string test;

想知道stl是怎么实现string的,发现string是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>

【问题讨论】:

    标签: c++ templates stl


    【解决方案1】:

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

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

    【讨论】:

    • 我刚刚重新检查了/usr/include/c++/4.8/bits/basic_string.h中basic_string的源代码,你可以看到:template&lt;typename _CharT, typename _Traits, typename _Alloc&gt; class basic_string
    • @Brian,非常感谢,它在 /usr/include/c++/4.8/bits/stringfwd.h 中声明
    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多