C++ Logo


Advanced search

std::string::insert and integer literal 0

From: Kilian Henneberger <kilis-mail_at_[hidden]>
Date: Wed, 7 Dec 2022 16:19:58 +0100
given a `std::string s;`, which overload of `std::string::insert` will `s.insert(0, 1, 'x')` call?
`std::(basic_)string` has several overloads of the member function `insert`. The two overloads of interest are
1. insert(size_type pos, size_type n, charT c)
2. insert(const_iterator p, size_type n, charT c)
These two overloads differ by their first parameter (`size_type` vs `const_iterator`). We all agree that the literal `0` is convertible to a `std::string::size_type`, therefore the first overload of `insert` is a valid candidate. Whether the second overload is a valid candidate, depends on whether `0` is convertible to `std::string::const_iterator` or not. If `std::string::const_iterator` is just a type alias for `const char*`, then `0` is convertible to it. This would mean that both overloads are valid candidates, and we get a compiler error as the call is ambiguous. But if `std::string::const_iterator` is a class type, then the first overload is a better match and will be called.
Thanks for your help and best regards,

Received on 2022-12-07 15:20:01