关于 std::bitset 构造函数的几个问题?

Several questions about constructors of std::bitset?

本文关键字:几个问题 bitset std 关于 构造函数      更新时间:2023-10-16

来自 cpp首选项

#3

template< class CharT, class Traits, class Alloc >
explicit bitset( const std::basic_string<CharT,Traits,Alloc>& str,
typename std::basic_string<CharT,Traits,Alloc>::size_type pos = 0,
typename std::basic_string<CharT,Traits,Alloc>::size_type n =
std::basic_string<CharT,Traits,Alloc>::npos);                                                    (until C++11)

template< class CharT, class Traits, class Alloc >
explicit bitset( const std::basic_string<CharT,Traits,Alloc>& str,
typename std::basic_string<CharT,Traits,Alloc>::size_type pos = 0,
typename std::basic_string<CharT,Traits,Alloc>::size_type n =
std::basic_string<CharT,Traits,Alloc>::npos,
CharT zero = CharT('0'),
CharT one = CharT('1'));                                                                                             (since C++11)
template< class CharT >

#4

explicit bitset( const CharT* str,
typename std::basic_string<CharT>::size_type n =
std::basic_string<CharT>::npos,
CharT zero = CharT('0'),
CharT one = CharT('1'));                                                                                            (since C++11)

我有几个问题:

  1. 对于#3#4,为什么标准指定std::basic_string<...>而不仅仅是std::string?我知道std::string也被称为std::basic_string<char>和其他字符类型,如wchar_tchar16_t可以应用于std::basic_string<...>。但我认为没有必要,因为bitset包含01,顾名思义。

  2. 老实说,我对string类不是很熟悉:为什么要添加#4const CharT*能做什么,这是std::basic_string<CharT,Traits,Alloc>无法实现的?

#3 对于使用宽字符的人来说很方便 - 你不能指望人们将宽"0"和"1"的字符串转换为窄字符串以使用基于字符串的构造函数,因为你碰巧知道值总是二进制的 - 否则这个构造函数应该替换为 1 位宽的字符串变体。 换句话说,它写得更方便,那么消除这种便利有什么好处呢?

#4 适用于具有字符串文字或指针到字符数组的人,这样他们就不需要构造无用的临时 std::string。