Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype( constexpr variable)

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
like image 778
Khurshid Normuradov Avatar asked Sep 07 '13 06:09

Khurshid Normuradov


People also ask

What is a constexpr variable?

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.

What does constexpr mean in C++?

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.

Why constexpr instead of define?

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

Is constexpr variable inline?

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.


1 Answers

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.

like image 195
Pierre Fourgeaud Avatar answered Sep 28 '22 18:09

Pierre Fourgeaud