c++ - 为 const char* 定义 std::begin 是否合法?

标签 c++ string string-comparison string-view

我有一个不区分大小写的字符串比较函数,它使用带有自定义比较器的 std::lexicographical_compare

不过,我希望能够比较stringsstring_viewsconst char* 彼此之间,以获得最大的便利性和效率。

所以我在想:如果我制作一个模板,std::stringbegin/endstd: :string_viewbegin/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 namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std 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

[namespace.std/1]

您可以改为在其他命名空间中声明它们,例如 ::

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 namespace std.

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.

[namespace.std]

关于c++ - 为 const char* 定义 std::begin 是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012276/

相关文章:

c++ - 使用 std::istream_iterator 从文件中读取二进制数据过早停止

c++ - C++ 检查关键字是否存在

c++ - jconsole 能否用于识别 JNI C++ 对象中的内存泄漏?

c - 精确的动态内存分配

java - 在 for 循环中连接字符串

c++ - 在 Linux 上找不到命令系统 ("pause")

c# - C# 中的 CRLF 解析布鲁斯

C#比较两个字符串数组

c# - 比较 2 个网址的最佳方式

java - 尝试编写我自己的字符串比较方法 - Java