How can I use std::is_constant_evaluated() without generating a warning [duplicate]

4 weeks ago 19
ARTICLE AD BOX

My understanding of std::is_constant_evaluated() is that it can be used as a condition in a if constexpr statement in order to invoke a constexpr function at compile time and fast function at runtime. This is I believe as per https://gist.github.com/Som1Lse/5309b114accc086d24b842fd803ba9d2

I have the following code

template <class T> constexpr T myAbs(const T &value) { if constexpr (std::is_constant_evaluated()) return value < TypeTraits<T>::zero ? -value : value; else { return T(std::abs(value.getValueAsDouble())); } }

The intent is to use a conditional expression at compile time, which may be slow, but is constexpr, then use std::abs at runtime, which may then be able to do some fast bit assignment or something at runtime. I am using C++20, so std::abs is not constexpr. As part of my unit testing I call myAbs with a static_assert

MyClass positive(5.0); MyClass negative(-5.0); static_assert (myAbs(positive) == positive, "Abs of a positive Physical should be itself"); static_assert (myAbs(negative) == positive, "Abs of a negative Physical should be the negative of itself");

In Visual Studio 2022 I get the warning

warning C5063: 'std::is_constant_evaluated' always evaluates to true in manifestly constant-evaluated expressions

My understanding is that I am using std::is_constant_evaluated() in the intended way, but perhaps I am not. Can anyone tell me how I would use it to avoid this compiler warning?

Read Entire Article