我有一个不区分大小写的字符串比较函数,它使用带有自定义比较器的 std::lexicographical_compare
。
不过,我希望能够比较strings
、string_views
和const char*
彼此之间,以获得最大的便利性和效率。
所以我在想:如果我制作一个模板,std::string
有begin
/end
,std: :string_view
有 begin
/end
, ... 但是 const char*
没有,甚至不是非-成员函数。
所以可以像这样定义自己的begin
/end
重载
namespace std {
const char * begin(const char* str) { return str; }
const char * end(const char* str) { return str + strlen(str); }
}
这样我就可以比较所有的东西了
std::lexicographical_compare(std::begin(a), std::end(a), std::begin(b), std::end(b), icomp );
?
如果没有,我还能如何解决我的问题?
最佳答案
不,这是不合法的,因为 const char *
不是用户定义的类型。
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespacestd
unless otherwise specified. A program may add a template specialization for any standard library template to namespacestd
only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited
您可以改为在其他命名空间中声明它们,例如 ::
const char * begin(const char* str) { return str; }
const char * end(const char* str) { return str + strlen(str); }
并将它们用于不合格的调用
std::lexicographical_compare(begin(a), end(a), begin(b), end(b), icomp );
此外,在 C++20 中,它将更加严格,只允许对程序定义类型进行类模板特化
Unless otherwise specified, the behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespacestd
.Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace
std
provided that (a) the added declaration depends on at least one program-defined type and (b) the specialization meets the standard library requirements for the original template.
关于c++ - 为 const char* 定义 std::begin 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012276/