Boost logo

Boost :

From: Robert Ramey (ramey_at_[hidden])
Date: 2021-08-24 15:59:15


On 8/23/21 10:20 AM, John Maddock via Boost wrote:

> I could be wrong, but I don't believe that that would be a valid use
> case, like you, the intended usage is to optimize runtime and compile
> time usage, ie:
>
> constexpr int f(int i)
>
> {
>
>   if(std::is_constant_evaluated())
>
>   {
>
>        // constexpr friendly code here
>
>   }
>
>   else
>
>   {
>
>     // Maybe use a function that's super fast but not constexpr safe
>
>   }
>
> }
>
> John.
>

I guess if it doesn't work, it's not valid. Certainly from what little
user documentation there is - cpp reference, there's no information on
this topic. My user case looks like:

template<typename T>
struct interval {
     T m_min;
     T m_ max;
     interval(const T & min, const T & max) :
         m_min(min),
         m_max(max)
     {}
}

template<typename T>
constexpr interval<T> get_interval(const T & t) {
     return std::is_constant_evaluated()
         ? interval<T>(t, t); // we know the value of t at compile time
so the range is effectively [t, t]
         : interval<T>(std::numeric_limits<T>::min(),
std::numeric_limits<T>::min()); // otherwise we won't know the value
until runtime so it could be in the range [...]
     ;
}

So I'm returning different values depending on whether we're compiling
or execution. In fact, if we know the value of t at compile time, the
runtime code will never be executed. So there would never be an
ambiguity, but of course the compiler can't see that so maybe that's why
the compiler is unhappy with this.

constexpr is a very useful facility. But like everything else in C++,
adding such a thing to the standard without experience, can create a lot
of problems.

Robert Ramey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk