1

Let's say I have this piece of code:

#include <iostream>

constexpr int myDumbFunction(int a, bool b);

int main(int argc, char **argv) {

    constexpr auto foo = 0;
    const auto bar         = 0;

    //! compile-time execution:
    std::cout << myDumbFunction(foo, true);

    //! runtime execution:
    std::cout << myDumbFunction(bar, true);

    return 0;
}

constexpr int myDumbFunction(int a, bool b) {
    if(a > 100 and b) {
        return a - 100;
    }
    else if(a < 100 and b) {
        return a + 100;
    }

    return 122;
}

Is there any way to detect if the first myDumbFunction() function call will be called at compile time?

In this particular example it's pretty obvious, but let's say that I don't know all the details about the objects that I'm passing around.

And another constexpr related question: are there some kind of asserts that won't change the compile-time execution?

mariusmmg2
  • 713
  • 18
  • 37
  • 1
    [Maybe related?](http://stackoverflow.com/questions/33964621/what-does-it-mean-to-poison-a-function-in-c) – Weak to Enuma Elish Mar 17 '16 at 19:30
  • The only way to make sure that it is called at compile time is to store its result in a `constexpr`. Currently, both can be done at runtime. – Jarod42 Mar 17 '16 at 19:55

1 Answers1

4
std::cout << std::integral_constant<int, myDumbFunction(foo, true)>::value;

is only valid if myDumbFunction is evaluated at compile time.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524