Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my code do one thing at compile-time, but another thing at run-time?

Tags:

I'm implementing a constexpr int foo(); function. In the body of foo(), I want to do something different (and possibly return something different) at compile time and something different at run-time.

With C++20, I can use std::is_constant_evaluated:

constexpr int foo() { return std::is_constant_evaluated() ? 123 : 456 };

but what if I'm using C++17 (or earlier) - what can I do with the same effect?

Note: Compiler-specific solutions are acceptable (though less desirable).

like image 359
einpoklum Avatar asked Nov 23 '20 14:11

einpoklum


People also ask

What is the difference between run time and compile time?

Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.

How Python does compile time and run time code checking?

Some portion of the Python coding is executed at compile time, but almost all the checking like name, type and so on, are deferred until code execution. So, if the Python code references a user-defined function that hardly exists, the code will run effectively.

Which errors are detected at compile time?

Compile-Time Errors: Errors that occur when you violate the rules of writing syntax are known as Compile-Time errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by the compiler and thus are known as compile-time errors.

What is used for a function to execute at compile time?

In computing, compile-time function execution (or compile time function evaluation, or general constant expressions) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time.


1 Answers

Note: Compiler-specific solutions are acceptable (though less desirable).

Let's mention the most obvious ones:

gcc has __builtin_is_constant_evaluated() at least documented since 9.2.0.

clang has the same builtin since clang-9.

like image 73
KamilCuk Avatar answered Sep 30 '22 19:09

KamilCuk