1

Since constexpr doesn't gives guarantee that it will be processed 'in-compile-time', I'd like to know some method to check if my code actually has been performed in compile-time or not.

Lets assume I have created some functor class, that on execution returns an array of values. I want it to be proceeded under compile-time.

#include "Functor.hpp"

constexpr Functor<int> functor_g; // not sure if should be static too
auto globalArray = functor_g(); // not sure if should be also const/constexpr

int main()
{
    // ...
}

Obviously I can't run any timers here because they requires run-time environment.

edit: I have confirmed it performs in compile-time by checking the assembly result under godbolt.org. Its a way for a small things, but still I would be grateful for some other methods.

max66
  • 65,235
  • 10
  • 71
  • 111
Piodo
  • 616
  • 4
  • 20
  • Just declare `globalArray` `constexpr`. It's only `constexpr` functions that needs to be callable at run-time as well. A `constexpr` variable though, has to be a compile-time constant. – super Feb 23 '20 at 09:21
  • I think the first paragraph under notes at [cppreference](https://en.cppreference.com/w/cpp/language/constexpr) is helpful. – BlameTheBits Feb 23 '20 at 11:34
  • Does this answer your question? [How to tell if \`constexpr\` is evaluated at compile time (without manual inspection)](https://stackoverflow.com/questions/52078752/how-to-tell-if-constexpr-is-evaluated-at-compile-time-without-manual-inspecti) – BlameTheBits Feb 23 '20 at 17:25

1 Answers1

3

How can I confirm that my constexpr expression has been actually performed in compile-time

You have to check the resulted assembly.

But you can only check the specific executable, with the specific compiler in the specific platform. You don't have guaranties that, also with different compilers, you get a compile-time execution from the same code.

From the language point of view, you can impose the compile-time execution, but never forget the "as-if rule" that "Allows any and all code transformations that do not change the observable behavior of the program".

To impose the compile-time execution (ignoring the "as-if rule"), you have to use the value returned from the constexpr function where a value is required compile-time.

Some examples (supposing the constexpr foo() function returns a std::size_t):

1) to initialize a constexpr variable

constexpr std::size_t bar = foo();

2) in a C-style array size

char bar[foo()];

3) in a template parameter

std::array<char, foo()>  bar;

4) in a static_assert() test

static_assert( foo() == 3u, "isn't three");
max66
  • 65,235
  • 10
  • 71
  • 111