C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Function only accepts parameter that will persist

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 6 May 2024 18:19:23 +0100
On Monday, May 6, 2024, Gašper Ažman wrote:

> P1690 - just use a different comparator. It already works.
>


But we still need a reform of consteval/constexpr functions. Firstly I
think the Standard should mandate that a constexpr function written as
follows:

constexpr bool Func(char const *const arg)
{
    if consteval
    {
        return true;
    }
    else
    {
        return false;
    }
}

Must always, when invoked in a constant-evaluated context, behave the same
as the following function:

consteval bool Func(char const *const arg)
{
    return true;
}

That is to say, the "if consteval" leg of a constexpr function must behave
exactly like a standalone consteval function. This isn't currently how
C++23 compilers behave -- all of the four big compilers give different
return values here. This is the first thing that needs to be fixed.

Furthermore, the following consteval function:

    template<size_t n>
    consteval bool Func(char const (&arg)[n])
    {
        return true;
    }

can be invoked with a non-const char array that may later change. We need a
way to specify, that not only is the argument consteval, but the object
referred to by the argument is also consteval. (I'm using the word
'consteval' here to mean 'never changes and persists forever').

Going back to the original idea of having a new standard library class
called 'std::efficient_string', which neglects to copy the string if it
knows for sure that the string is const static-duration, well the
constructor (and also assignment operator) for such a class would need:
    a) To be marked 'constexpr' so that it can be invoked in both a
constant-evaluated context and also in a runtime context.
    b) The 'consteval' leg would only be entered if the argument (and in
the case of pointers or references: also what the argument refers to) is
consteval.

I order to achieve (b), maybe we should apply 'consteval' to the reference
as follows:

    template<size_t n>
    consteval bool Func(char const (&consteval arg)[n])
    {
        return true;
    }

Received on 2024-05-06 17:19:26