What's the purpose of std::char_traits::assign()?

Viewed 931
void assign(char_type& to, char_type from);

Why can't you just use the assignment operator instead of using this function? What is this used for?

3 Answers

You can write your own character class, and define its operator=. But, you may find it convenient to use fundamental character types such as char, wchar_t, char16_t, char32_t or char8_t. Such non-class types don't allow you to overload their operators, and so char_traits provides a way to customise a small set of their common operations (as suggested in other answers, this could allow case-insensitive character operations, for example).

template < 
  class CharT, 
  class Traits = std::char_traits<CharT>, 
  class Allocator = std::allocator<CharT>
> class basic_string;

std::basic_string is a good example; the second template parameter, Traits, allows access to such customisation. Consider also the third template parameter, Allocator, which allows the user of std::basic_string to customise how it allocates memory internally. This could lead to a similar question: why not just use operator new?

Less significant, but note too that C++20 has introduced a second overload of std::char_traits<CharT>::assign:

static constexpr char_type* assign(char_type* p, std::size_t count, char_type a);
Related