constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.
The easiest way to check whether a function (e.g., foo ) is constexpr is to assign its return value to a constexpr as below: constexpr auto i = foo(); if the returned value is not constexpr compilation will fail.
We allow annotating a function parameter with constexpr with the same meaning as a variable declaration: must be initialized with a constant expression.
A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type.
I need to write a constexpr addressof function, but I find it impossible. Does anyone know if this is possible?
A reference implementation in at cppreference.com:
template< class T >
T* addressof(T& arg)
{
return reinterpret_cast<T*>(
&const_cast<char&>(
reinterpret_cast<const volatile char&>(arg)
)
);
}
uses reinterpret_cast (similarly to GCC implementation), so it will not do. I can see that the latest C++ Standard draft, N3485 also does not require that addressof() be constexpr even though lots of functions form header <utility> have ben recently upgraded to constexpr.
A possible, although not very convincing or useful use-case for it would be:
constexpr MyType m;
constexpr MyType const* p = &m; // this works today
constexpr MyType const* p = addressof(m); // this is my question
Imagine that MyType has overloaded operator&.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With