0

I have declared the following in header file.

namespace G1
{
    inline namespace V1
    {
        constexpr float getV();
    }
}

In CPP file, I have defined the getV function as

constexpr float G1::V1::getV()
{
    return 0.1f;
}

In the main I am using static_assert to compare the version as shown.

int main()
{
    static_assert( G1::getV() == 1.0f, "Error"); // Please Ignore the way I am comparing the floats
    return 0;
}

But when I compile the code, I am getting expression did not evaluate to a constant.

Am I doing anything wrong here? I am using VS2015. Thanks in advance

4
  • == instead of = to compare. Commented Dec 6, 2017 at 16:24
  • Sorry for the typo, I modified the compare. Commented Dec 6, 2017 at 16:25
  • 5
    Are both functions in the same file? Otherwise, how is the main function supposed to know what getV() returns? Commented Dec 6, 2017 at 16:26
  • @BoPersson: I have included the header, the one in which I have declared the namespace and also the function declaration. Commented Dec 6, 2017 at 16:28

2 Answers 2

4

In practice, the C++ compilation model is 2 phase. First you compile, then you link.

constexpr only works in the compile phase. There is no requirement that compilers can fold constexpr function bodies into call sites when doing so would require link-time constexpr evaluation.

So when you fail to provide a body for your constexpr function, anyone that cannot see that body will not evaluate it at compile time, but rather wait until runtime.

constexpr doesn't mean "will be run at compile time", but rather "could be run at compile time in some situations".

Sign up to request clarification or add additional context in comments.

Comments

2

If you want the compiler compiling main to know about the value getV returns at compile time, you must implement the function in the header too. Since you use static_assert the definition is needed at compile time.

The way you do it only the compiler of the .cpp file containing getV can know what it returns. This is usually a different compiler call.

By link time, it is too late to check the static_assert.

The error message: expression did not evaluate to a constant is caused by the compiler not knowing the implementation. In a "runtime" context it would insert a call here, to be later fixed up by the linker and executed at runtime. A runtime call is however never a compile time constant.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.