Question

Why decltype of constexpr variable is failed ?

#include <cstdint>
#include <type_traits>

constexpr uint16_t foo(){ return 0;}

constexpr auto cv = foo();
          auto v  = foo();

static_assert( std::is_same< uint16_t, decltype(cv)>::value, "!"); // failed

static_assert( std::is_same< uint16_t, decltype(v) >::value, "!"); // success
Was it helpful?

Solution

decltype(entity) specifies the declared type of the entity specified by this expression.

Due to the constexpr, (A constexpr specifier used in an object declaration implies const), your cv variable is of type const uint16_t.

You know that const uint16_t is different from uint16_t then your line:

static_assert( std::is_same< uint16_t, decltype(cv)>::value, "!");

fail as this is expected.


The line

constexpr uint16_t foo(){ return 0;}

specifies that the function foo can be evaluated at compile time but the function still returns a uint16_t. That why on the line

auto v  = foo();

v is of type uint16_t then the line

static_assert( std::is_same< uint16_t, decltype(v) >::value, "!");

works as expected too.

OTHER TIPS

decltype(name) gives the type of the entity to which name refers. (Note this is different behaviour from decltype((name)) or decltype(other-expr))

The variable cv has type const uint16_t (due to the constexpr - constexpr implicitly declared a variable const), which is a different type from non-const uint16_t. Therefore the static_assert fails.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top