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: Thu, 2 May 2024 12:39:52 +0100
On Wed, May 1, 2024 at 3:37 PM Frederick Virchanza Gotham wrote:
>
> Then the constructor for 'efficent_string' would be able to pick out
> the times when it's not necessary to copy the string.


I have two questions. Firstly, why did the committee choose that the
following would be an ambiguous overload?

    bool Func(char const (&arg)[6u])
    {
        return true;
    }

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

when invoked with a string literal as follows:

    Func( "Hello" );

The following strategy would have made more sense:
    Step 1: Attempt to pass the argument 'as is'
    Step 2: Decay the argument, then try to pass it

Why was the decision made to force a compiler error here instead of
trying Step 1 followed by Step 2?

Moving onto my second question. . .

Consider the following function:

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

    int main(int const argc, char **const argv)
    {
        std::cout << Func("Hello") << std::endl;
    }

The above snippet prints "1" on GNU g++, LLVM clang++ and Intel ICX.
However if I change that first word from 'consteval' to 'constexpr' as
follows:

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

Then all three compilers print out "0". This doesn't make sense. Why
is it this way?

The reason I'm asking these questions is that I think I need to
propose changes to the core language in order to implement an
"std::efficient_string". I would like for 'efficient_string' to have
two constructors as follows, and I would like for the constructor that
accepts a reference to an array to take precedence over the
constructor that takes a pointer (instead of the compiler issuing a
diagnostic about an ambiguity).

        template <std::size_t n>
        constexpr efficient_string(char const (&arg)[n])
        {
            if consteval
            {
                // don't copy the string
            }
            else
            {
                // copy the string
            }
        }

        constexpr efficient_string(char const *const arg)
        {
            if consteval
            {
                // don't copy the string
            }
            else
            {
                // copy the string
            }
        }

Received on 2024-05-02 11:40:05