C++ Logo

std-proposals

Advanced search

Re: Are constrained type barred from std:: implementations?

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Fri, 20 Aug 2021 15:05:17 +0300
On Fri, 20 Aug 2021 at 11:43, DBJ via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> I can see (for example) static_assert being used in basic_stringview to constrain the instantiation of it. Not the type definition.
>
> Thus I am wondering what was/is wrong with using C++20 require, for example?

> template <class _Elem, class _Traits>
> #if __cplusplus >= 202002L
> // C++20 (and later) code
> requires // requires-clause (ad-hoc constraint)
> is_same_v<_Elem, typename _Traits::char_type> &&
> (!is_array_v<_Elem>)&&is_trivial_v<_Elem>&& is_standard_layout_v<_Elem>
> #endif
> class basic_string_view { // wrapper for any kind of contiguous character
> // buffer
> public:
> #if __cplusplus < 202002L
> // apparently standard was/is barring std:: types to be constrained?
> // ditto this is instantiation constraint
> // as present in MS STL today
> static_assert(is_same_v<_Elem, typename _Traits::char_type>,
> "Bad char_traits for basic_string_view; "
> "N4659 24.4.2 [string.view.template]/1 \"the type "
> "traits::char_type shall name the same type as charT.\"");

Well, string_view needs to work in C++17 mode, so rather than doing
that both with a constraint and with a static_assert,
an implementation vendor can easily choose to use just a
static_assert. And as others have hinted, a static_assert allows
the library writer to decide the text of the diagnostic, which can be
beneficial.

Received on 2021-08-20 07:05:31