
On November 16, 2012 10:27:33 AM Antony Polukhin <antoshkka@gmail.com> wrote:
2012/11/16 Yanchenko Maxim <maximyanchenko@yandex.ru>:
Marshall. low <mclow.lists. at> gmail.com> writes:
Please let me know what you think!
As probably everyone, we have our own device for this. Here are some points and experience we gathered.
1. This class is essentially just an iterator_ range<char*> (modulo template for const/wchar_t), so it should either inherit from it or have corresponding converting ctors/operators. In this sense Olaf/Gennadiy's remarks are pretty valid. OTOH size is needed very frequently and having it precomputed is a good thing, so conversion approach seems to be better (but then we lose passing by reference as iterator_range, type_traits etc). I'm not sure what's more important.
+1 for having corresponding explicit converting ctors/operators.
As long as iterator_range uses the begin()/end() protocol and string_ref has the corresponding member functions it should work without any special constructors/operators, shouldn't it?
2. Given the above, the name is misleading as it's not a reference to std::string. We use name char_range.
Better then other names, but at first glance it is not clear, that char_range can be used as string.
I'll add external_string or ext_string as alternative (because it operates on characters in an external storage).
3. It's worth having a static constructor 'literal' (templated with size) to construct char_ranges from literals - as the compiler knows their size in compile time (minus zero terminator). It can be a constexpr too. Same manner - static function 'from_array', embrasing an array of chars in whole, assuming there is no zero terminator - useful for working with structures representing messages in char-based protocols with fixed-width fields.
Instead of 'literal' I'd propose a following constructor:
template <size_type N> explicit string_ref(const Char (&str)[N]);
-1 for constructor, +1 for static member or free function generator. Restricting it to constant string literals involves SFINAE machinery (which definitely is worth being implemented in a library rather being written by users). But even with SFINAE it's not 100% bullet proof. The user has to explicitly show that he knows that the characters are a literal and he knows what he is doing. FWIW, I've written my own basic_string_literal class that only operates on string literals and has the necessary SFINAE protection and a free function generator. It pretty much resembles a read-only std::string otherwise.