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
constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time. Your code may have been executed before you run it.
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.
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.
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.
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