Opened 6 years ago

Closed 5 years ago

#12980 closed Feature Requests (wontfix)

compile time character array

Reported by: gast128@… Owned by: Marshall Clow
Milestone: To Be Determined Component: utility
Version: Boost 1.63.0 Severity: Optimization
Keywords: Cc:

Description

The string_view has the following constructor:

BOOST_CONSTEXPR basic_string_view(const charT* str)
        : ptr_(str), len_(traits::length(str)) {}

This uses a 'length' call to determine its length. It would be nice if it could differentiate between compile time array's and other strings. However others have failed as well:

http://stackoverflow.com/questions/36459703/compile-time-strings-constructor-overload-precedence-between-const-char

Change History (4)

comment:1 by Marshall Clow, 6 years ago

Owner: changed from No-Maintainer to Marshall Clow

As you note, we've been down this rathole before. You can pass pointer and length; there's a constructor for that.

And then there's the whole "trailing null" issue:

const char arr1 [] = { 'H', 'e', 'l', 'l', 'o' };
const char arr2 [] = "Hello";
const *char p1 = "Hello";

If you make a string_view from arr1, its size() should be five, because there are five characters in the array.

If you make a string_view from p1, its size() should be five, because that's what traits::length returns.

What about arr2? Should it be 6, since there are six characters in the array? Or 5, since the last character is a NUL?

Last edited 6 years ago by Marshall Clow (previous) (diff)

comment:2 by gast128@…, 6 years ago

The trailing zero is indeed a conceptual problem of how to deal with character arrays vs string literals. Alternatively could it be solved by introducing yet another class / macro and overload for that, e.g.

BOOST_DEFINE_STRING_CONST(_T("Hello"));  //introduces a class convertible to string_view

In our code base we largely use (w)strings. A reason to prefer the string_view in arguments is to circumvent the superfluous conversion to a string object when hard code strings are supplied in the arguments.

comment:3 by gast128@…, 5 years ago

Or

#define BOOST_DEFINE_STRINGA_VIEW(str)  \
    string_view((str), _countof((str)) - 1)

Drawbacks that it is not much of an improvement and that Stroustrup doesn't like macro's.

comment:4 by Marshall Clow, 5 years ago

Resolution: wontfix
Status: newclosed

Drawbacks that it is not much of an improvement.

Yes, I think this is not really an improvement.

In C++17, we got a constexpr char_traits::length, specifically to solve this problem. People can do that with boost::string_view as well (define their own traits class, with a constexpr length call).

Closing this as "wont fix" (even though it's not a bug, but a feature request)

Note: See TracTickets for help on using tickets.