decltype( constexpr variable)

依然范特西╮ 提交于 2021-02-16 16:13:00

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18670518/decltype-constexpr-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!