C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Thu, 02 May 2024 08:20:03 -0700
On Thursday 2 May 2024 08:03:56 GMT-7 Frederick Virchanza Gotham via Std-
Proposals wrote:
> 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?

Use __builtin_constant_p(*x). So yes, you need compiler support.

Our experience with this in QStringView, QAnyStringView is that it's very hit-
and-miss. The strings' constantness disappears from the compiler's view very
quickly, depending on what gets inlined and what doesn't. Moreover, sometimes
the compiler fails to execute the constexpr code at constexpr time and instead
inserts the code to be run at runtime... a worse outcome than if we didn't try
to optimise.

https://codereview.qt-project.org/c/qt/qtbase/+/476324
https://codereview.qt-project.org/c/qt/qtbase/+/533635
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114088 for the proper solution

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Principal Engineer - Intel DCAI Cloud Engineering

Received on 2024-05-02 15:20:10