Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can addressof() be implemented as constexpr function?

Tags:

People also ask

What functions can be constexpr?

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.

How do I know if a function is constexpr?

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.

Can a function parameter be constexpr?

We allow annotating a function parameter with constexpr with the same meaning as a variable declaration: must be initialized with a constant expression.

Can a function return constexpr?

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&.