[英]Why is basic_string_view not limited to character types?
Browsing twitter I found this example of C++23 code.浏览twitter我发现了这个 C++23 代码示例。
This is my adaptation of it, to make more obvious what I am interested about(I do not care about dangling problems mentioned in replies).这是我对它的改编,以使我感兴趣的内容更加明显(我不关心回复中提到的悬空问题)。
#include <vector>
#include <string_view>
#include <iostream>
#include <type_traits>
int main() {
std::vector v{84.72};
std::basic_string_view sv = v;
static_assert(std::is_same_v<decltype(sv), std::basic_string_view<double>>);
const auto val = *std::begin(sv);
std::cout << val;
}
My question is why isn't there some requires/concept constraint on the basic_string_view
to make it work only with char ish types, so basic_string_view<double>
in this example would not compile?我的问题是为什么在
basic_string_view
上没有一些要求/概念约束以使其仅适用于 char ish类型,所以在这个例子中basic_string_view<double>
不会编译?
I suspect that this is a char
-like type:我怀疑这是一个类似
char
的类型:
struct Char {
char c;
Char() : c{} {}
Char(char c) : c{c} {}
};
Why shouldn't it work?为什么它不应该工作? Indeed it does
确实如此
std::basic_string<Char> str{'a', 'b'}; // OK
std::cout << str[0].c << std::endl; // prints a
std::cout << str.length() << std::endl; // prints 2
And what makes that class special with respect to, say, this?是什么让 class 在这个方面特别?
struct Char {
int c;
Char() : c{} {}
Char(int c) : c{c} {}
};
Nothing, except our decision that char
is a character and int
is not.什么都没有,除了我们决定
char
是一个字符而int
不是。 (And that's exactly the reason why I had to write std::cout << str[0].c
and couldn't write std::cout << str
or std::cout << str[0]
, because <<
is overloaded for char
s and maybe something else, but certainly not for my own types.) (这正是我必须写
std::cout << str[0].c
并且不能写std::cout << str
或std::cout << str[0]
的原因,因为<<
对于char
s 或者其他东西来说是重载的,但对于我自己的类型来说肯定不是。)
So the bottom line, as implied by some comments, is a counter-question:因此,正如一些评论所暗示的那样,底线是一个反问题:
How would you define a "charish" type?
你会如何定义“魅力”类型?
which I would rephrase as我会改写为
Can we encode the definiton of "sequence of
char
-like objects" in a concept?我们可以在一个概念中编码“类似
char
的对象的序列”的定义吗?
which leads in turn to another question:这又导致了另一个问题:
What operations can you do only on a "sequence of
char
-like objects" that you can't do on all "sequences of non-char
-like objects"?您只能对“类似
char
的对象的序列”执行哪些操作,而不能对所有“类似char
的对象的序列”执行哪些操作?
I can't think of one.我想不出一个。
So if you wanted to enforce the constraint you mention, you would end up explicitly listing char
, wchar
, and all the others in some SFINAE thing.因此,如果您想强制执行您提到的约束,您最终会在某些 SFINAE 事物中明确列出
char
、 wchar
和所有其他约束。
And then you couldn't use it with any other type.然后你不能将它与任何其他类型一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.