std::ranges::cdata

From cppreference.com
< cpp‎ | ranges
 
 
 
Defined in header <ranges>
inline namespace /*unspecified*/ {

    inline constexpr /*unspecified*/ cdata = /*unspecified*/;

}
(since C++20)
(customization point object)
Call signature
template< class T >

    requires /* see below */

constexpr std::remove_reference_t<ranges::range_reference_t</*CT*/>>* cdata(T&& t);

Returns a pointer to the first element of a contiguous range denoted by a const-qualified argument.

Let CT be

  1. const std::remove_reference_t<T>& if the argument is an lvalue (i.e. T is an lvalue reference type),
  2. const T otherwise,

a call to ranges::cdata is expression-equivalent to ranges::data(static_cast<CT&&>(t)).

If ranges::cdata(t) is valid, then it returns a pointer to a object.

Expression-equivalent

Expression e is expression-equivalent to expression f, if e and f have the same effects, either are both potentially-throwing or are both not potentially-throwing (i.e. noexcept(e) == noexcept(f)), and either are both constant subexpressions or are both not constant subexpressions.

Customization point objects

The name ranges::cdata denotes a customization point object, which is a const function object of a literal semiregular class type (denoted, for exposition purposes, as cdata_ftor). All instances of cdata_ftor are equal. Thus, ranges::cdata can be copied freely and its copies can be used interchangeably.

Given a set of types Args..., if std::declval<Args>()... meet the requirements for arguments to ranges::cdata above, cdata_ftor will satisfy std::invocable<const cdata_ftor&, Args...>. Otherwise, no function call operator of cdata_ftor participates in overload resolution.

Example

#include <cstring>
#include <iostream>
#include <ranges>
#include <string>
 
int main()
{
    std::string src {"Hello world!\n"};
 
    char dst[20]; // storage for a C-style string
    std::strcpy(dst, std::ranges::cdata(src));
    // [data(src), data(src) + size(src)] is guaranteed to be an NTBS
 
    std::cout << dst;
}

Output:

Hello world!

See also

obtains a pointer to the beginning of a contiguous range
(customization point object)
(C++17)
obtains the pointer to the underlying array
(function template)