NoSenseEtAl
NoSenseEtAl

Reputation: 30028

Why is basic_string_view not limited to character types?

Browsing twitter I found this example of C++23 code.

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 charish types, so basic_string_view<double> in this example would not compile?

Upvotes: 5

Views: 335

Answers (1)

Enlico
Enlico

Reputation: 28416

I suspect that this is a char-like type:

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?

struct Char {
    int c;
    Char() : c{} {}
    Char(int c) : c{c} {}
};

Nothing, except our decision that char is a character and int is not. (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 chars and maybe something else, but certainly not for my own types.)

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?

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"?

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.

And then you couldn't use it with any other type.

Upvotes: 3

Related Questions