Boost logo

Boost :

Subject: Re: [boost] [program_options] Some methods take const char*, others take std::string
From: Yakov Galka (ybungalobill_at_[hidden])
Date: 2011-08-15 02:57:34


It's not just for saving typing, it's for making the interface more generic.
Consider the following:

void f(const char*);
void f(const std::string&);

I can use it for null-terminated strings and for std::srings just fine. But
consider the case I want to pass it a sub-string of some string, or a string
stored in std::vector, or a non-null terminated string:

std::string str1 = ...;
std::vector<char> str2 = ...;
char str3[1024];
GetBinaryPacket(str3);

f(str1.substr(1, 5)); // unnecessary copy
f(std::string(str2.begin(), str2.end())); // unnecessary copy
f(std::string(str3, str3 + 5)); // unnecessary copy

Compare it with:

typedef iterator_range<const char*> str_ref;
void f(str_ref);

f(str_ref(str1.data()+1, str1.data()+6)); // no copy
f(str_ref(&str2[0], &str2[0] + str2.size())); // no copy
f(str_ref(str3, str3 + 5)); // no copy

Ok, so the above is longer than the first because we didn't define a nice
interface of str_ref yet, but it demonstrated the generality.

Note that the most general way is to use templates accepting any Range of
chars, just as boost string algorithms do. But this is not good for separate
compilation, so the above is the best compromise of efficiency, separate
compilation and generality we can get.

Yakov

On Mon, Aug 15, 2011 at 01:45, Gabriel Redner <gredner_at_[hidden]> wrote:

> On Thu, Aug 11, 2011 at 4:45 AM, Yakov Galka <ybungalobill_at_[hidden]>
> wrote:
> > Another option is to define
> >
> > class str_ref : public iterator_range<const char*> { ... };
> >
> > Convertible from both, string literals and std::strings, and provide only
> > one overload that accepts it everywhere.
> >
> > Just an idea.
> > --
> > Yakov
>
> Hi Yakov,
>
> Thanks for your suggestion! In the end though, I decided to add
> separate std::string overloads. Since the interfaces involved are few
> and simple, it seemed better to overload in the most straightforward
> way, rather than add something fancier just to save a bit of typing on
> the implementation side.
>
> Thanks,
> -Gabe
> _______________________________________________
> Unsubscribe & other changes:
> http://lists.boost.org/mailman/listinfo.cgi/boost
>

-- 
Yakov

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk