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 16:03:56 +0100
On Thu, May 2, 2024 at 12:39 PM Frederick Virchanza Gotham wrote:
>
> Then all three compilers print out "0". This doesn't make sense. Why
> is it this way?


I've made a bit of progress on this. The following program prints out:

    1
    0
    0

on GNU g++, LLVM clang++, Intel ICX and also Microsoft Visual C++.
Here's the code:

    #include <cstddef> // size_t
    #include <iostream> // cout, endl
    #include <type_traits> // is_same, remove_cv, remove_cvref, remove_pointer

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

    template<typename T>
    requires std::is_same_v<
        char,
        std::remove_cv_t< std::remove_pointer_t< std::remove_cvref_t<T> > >
>
    constexpr bool Func(T &&arg)
    {
        if ( std::is_constant_evaluated() ) { return true; }
        return false;
    }

    int main(int const argc, char **const argv)
    {
        using std::cout, std::endl;

        cout << Func("Hello") << endl;
        cout << Func(argv[0]) << endl;

        constexpr char const *x = "Goodbye";
        cout << Func(x) << endl;
    }

Some how some way, this combination of template functions allows all 4
compilers to pick out "Hello" as a compile-time constant. However it
fails on all 4 compilers to identify 'x' as a compile-time constant.

Anyone got any ideas to get it to recognise 'x' as a compile-time
constant? Or would we need a change to the core language?

Received on 2024-05-02 15:04:09