Home > Backend Development > C++ > Can We Determine if a C 11 Expression is `constexpr` at Compile Time Without Declarations?

Can We Determine if a C 11 Expression is `constexpr` at Compile Time Without Declarations?

Susan Sarandon
Release: 2024-12-02 12:58:11
Original
969 people have browsed it

Can We Determine if a C  11 Expression is `constexpr` at Compile Time Without Declarations?

Utilizing constexpr in C 11: Determining Constant Expressions

Question:

Is it feasible to ascercerain whether a C 11 expression qualifies as a constant expression (constexpr) during compile-time without relying on declarations?

Answer:

Utilizing the noexcept operator, it is possible to construct a compile-time boolean indicating whether an expression constitutes a constexpr:

template<typename T>
constexpr typename remove_reference<T>::type makeprval(T&& t) {
  return t;
}

#define isprvalconstexpr(e) noexcept(makeprval(e))
Copy after login

Explanation:

The noexcept(e) expression validates the following conditions:

  • The absence of function calls with non-throwing exception specifications or variable calls that do not constitute constant expressions.
  • No presence of "throw" expressions.
  • No dynamic casts or typeids in the form of throwables.

Limitations:

Due to the conservative nature of "potentially evaluated" expressions, there may be instances where noexcept may provide false negatives. For example:

constexpr int a = (0 ? throw "fooled!" : 42);
constexpr bool atest = isprvalconstexpr((0 ? throw "fooled!" : 42)); // returns false
Copy after login

In this case, a is initialized successfully, but atest evaluates to false because the throw expression is potentially evaluated, even though it is never executed.

The above is the detailed content of Can We Determine if a C 11 Expression is `constexpr` at Compile Time Without Declarations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template