user1095108 user1095108 - 1 year ago 59
C++ Question

is it a good style to compare strings this way?

I have this in mind to use in a

.cpp
file:

namespace
{
bool operator==(char const* const a, char const* const b) noexcept
{
return !::std::strcmp(a, b);
}
}


Is this good style?

EDIT:

I think the tasteful c++1z way, that accomplishes the same thing, would be to use the new
std::string_view
class for comparisons.

Answer Source

You can't overload operator which doesn't take class or enum as its operands, which means you can't change the behavior they work with build-in types.

When an operator appears in an expression, and at least one of its operands has a class type or an enumeration type, then overload resolution is used to determine the user-defined function to be called among all the functions whose signatures match the following:

I'll suggest you to use std::string intead of char*, which provide operator==. Then you can avoid using of std::strcmp(), and such kind of c-style string functions at all. If you do need a c-style string, you can use std::basic_string::c_str() to convert it back when necessary.