Document Number: P0555R0, ISO/IEC JTC1 SC22 WG21
Audience:LEWG
Date:2017-01-30
Author:Axel Naumann (axel@cern.ch)

string_view for source_location

Table of Contents

 

I have a great respect for incremental improvement, ...
[followed by words that we don't care about here.]
 
- Steve Jobs; Interview with The Rolling Stone, 1994

Introduction

Access to the null-terminated byte string (NTBS) as returned by some of the member functions of source_location is unwieldy in constexpr contexts. This paper tries to explain and fix the issue.

Motivation

What constexpr strings need is a pointer to the start of the NTBS and its length. It is expected that constexpr string classes — whatever their shape will be — can be constructed from those two ingredients. We have a wonderful example for such a constexpr string class in p0259. An example for a constexpr context for source_location and strings is the Static Reflection paper (p0194).

source_location is a constexpr object: all its state is defined at translation time. All its members are constexpr. Yet, building a constexpr string object out of the values returned by file_name() and function_name() is non-trivial, as the NTBS length needs to be determined first. That is traditionally done by strlen [cstring.syn] which is not marked constexpr. Instead, a constexpr loop must be written to determine the position of the trailing \0 character.

To facilitate handling the NTBS returned by source_location, this paper proposes to instead return string_view, which gives access to the NTBS value for instance through front(), and to its length through length(), both of which are constexpr.

Proposed wording

The wording is relative to n4529. Insertions and deletions are marked the usual way. Grayish background indicates proposed wording.

In 14.1.1 Header <experimental/source_location> synopsis [reflection.src_loc.synop] change:


// 14.1.3, source_location field access
constexpr uint_least32_t line() const noexcept;
constexpr uint_least32_t column() const noexcept;
constexpr const char*string_view file_name() const noexcept;
constexpr const char*string_view function_name() const noexcept;

In 14.1.3 source_location field access [reflection.src_loc.fields] change:

constexpr const char*string_view file_name() const noexcept;

Returns:
TheA string_view on the presumed name of the current source file (C++14 ยง16.8) represented by this object as an NTBS.

constexpr const char*string_view function_name() const noexcept;

Returns:
If this object represents a position in the body of a function, returns a string_view on an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty stringstring_view.