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

c++, char, char-traits

Solution

You actually use this function every time you use std::string :). std::string is actually a typedef for std::basic_string, which is defined as:

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

(see this). Pay particular attention to the Traits template parameter. If you were so inclined, the Traits template parameter allows you to customize certain attributes of the string class's behavior. One of these properties is what happens when you make an assignment.

Here is an example usage of this. It will force assignments to be lowercase.

#include <string>
#include <iostream>
#include <cctype>

struct ci_char_traits : public std::char_traits<char> {
    static void assign(char& r, const char& a)
    {
        r = std::tolower(a);
    }

    static char* assign(char* p, std::size_t count, char a)
    {
        for (std::size_t i = 0; i < count; ++i)
        {
            p[i] = std::tolower(a);
        }
    }
};

typedef std::basic_string<char, ci_char_traits> ci_string;

std::ostream& operator<<(std::ostream& os, const ci_string& str) {
    return os.write(str.data(), str.size());
}

int main()
{
    ci_string s1 = "Hello";

    // This will become a lower-case 'o'
    s1.push_back('O');

    // Will replace 'He' with lower-case 'a'
    s1.replace(s1.begin(), s1.begin()+2, 1, 'A');

    std::cout << s1 << std::endl;
}

Problem

``` 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?

Original source