C++ Logo

std-proposals

Advanced search

Re: why does std::basic_string should accept an std::basic_string_view with the same charT and Traits

From: Nikolay Mihaylov <nmmm_at_[hidden]>
Date: Sun, 13 Sep 2020 21:08:17 +0300
if you looking for equality, fastest way is:

template<class T1, class A1, class T2, class A2>
bool operator==(const std::basic_string<char, T1, A1> &a, const
std::basic_string<char, T2, A2> &b){
if (a.size() == b.size())
return memcmp(a.c_str(), b.c_str(), a.size()) == 0;
return false;
}

template<class T1, class A1, class T2, class A2>
bool operator!=(const std::basic_string<char, T1, A1> &a, const
std::basic_string<char, T2, A2> &b){
return ! (a == b);
}

however, the compiler *knows* what strcmp is , so if you do
strcmp(a.c_str(), b.c_str()) == 0;
it generates code similar to the one above.
gcc / clang even replaces it with bultin_strcmp / bultin_memcmp that uses
SSE so performance is even great.

In the example I was using strcmp() because it also can do < <= => > as
well.
Take a look how I did it here:
https://github.com/nmmmnu/HM4/blob/1.0.0/include/stringref.h

On Sun, Sep 13, 2020 at 6:58 PM Thiago Macieira via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Sunday, 13 September 2020 05:57:43 PDT Nikolay Mihaylov via
> Std-Proposals
> wrote:
> > 3. you can use strcmp() - my favourite option but I like low lever stuff.
> > 4. with cpp17 you can convert string to string view then compare string
> > view's - convertion will be removed from the optimizer and you will get
> > strcmp() under the hood.
>
> Note that it's memcmp() we're talking about, not strcmp().
>
> --
> Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
> Software Architect - Intel DPG Cloud Engineering
>
>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2020-09-13 13:08:56