Home > front end >  Question on basic_string.h implementation
Question on basic_string.h implementation

Time:11-17

I was looking at the basic_string.h implementation to understand more and try to compile it in a separate namespace. I have the below compile error and was confused. I am using gcc compiler 12.1

basic_string.h: error: wrong number of template arguments (1, should be 3)
operator==(const basic_string<_CharT>& __lhs,

The template for basic_string class has 3 arguments

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

However, in later part of the code, I saw that when they try to overload the operator==, they use basic_string with only 1 argument, i.e. <_CharT>.

template <typename _CharT>
inline typename __gnu_cxx::__enable_if<std::__is_char<_CharT>::__value,
                                       bool>::__type
operator==(const basic_string<_CharT>& __lhs,
           const basic_string<_CharT>& __rhs) _GLIBCXX_NOEXCEPT {
  return (__lhs.size() == __rhs.size() &&
          !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
                                             __lhs.size()));
}

How did it work in the std namespace and not working in my own namespace?

CodePudding user response:

The file you are referencing is <bits/basic_string.h> in the standard library path of the libstdc standard library implementation.

As you are saying it defines std::basic_string without providing default arguments to any of its three template parameter.

However the standard requires that the second and third be defaulted to std::char_traits<CharT> and std::allocator<CharT> respectively where CharT is the first template parameter.

So std::basic_string<CharT> should be just fine. It should be the same as std::basic_string<CharT, std::char_traits<CharT>, std::allocator<CharT>>.

Libstdc is implementing this requirement by including another file <bits/stringfwd.h> at the top of the <bits/basic_string.h> file. In this file std::basic_string is forward declared with the default arguments provided as required above.

You probably did not correctly copy the necessary content from this header.

But even when copying all necessary declarations, as I already pointed out in my comment, there won't be any guarantee that what you are trying to do will work anyway. The implementation may assume that it is located in the std namespace. It may also use macros, pragmas or compiler builtins that only work as intended in the standard library implementation headers. And in user code all identifiers starting with an underscore followed by an upper-case letter or containing a double underscore may not be used. They are reserved specifically to the standard library and compiler implementation.

  •  Tags:  
  • c
  • Related