简体   繁体   English

为什么 std::declval 不是 constexpr?

[英]Why is std::declval not constexpr?

As in question - why is code like this illegal in cpp?如题 - 为什么这样的代码在 cpp 中是非法的?

static_assert(std::declval<std::array<int, 4>>().size() == 4);

Is it an overlook in standard or there is some deeper rationale why std::declval is not constexpr ?它是标准的忽视还是有一些更深层次的理由为什么std::declval不是constexpr

This line:这一行:

static_assert(std::declval<std::array<int, 4>>().size() == 4);

fails to compile, because you are using declval in an evaluated context.无法编译,因为您在评估的上下文中使用declval This is not allowed, and if you do that your program is ill-formed.这是不允许的,如果你这样做,你的程序是错误的。 declval can only be called in unevaluated contexts such as in a decltype or sizeof . declval只能在未评估的上下文中调用,例如在decltypesizeof中。

Making a function constexpr means that it can be called at either run-time, or compile-time.制作 function constexpr意味着它可以在运行时或编译时调用。 Since declval simply can't be called, there's no point making it constexpr .由于declval根本无法被调用,因此将其constexpr毫无意义。 I suppose there wouldn't be any harm in making it constexpr , but either way, it doesn't matter.我想将其设为constexpr不会有任何危害,但无论哪种方式,都没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM