Reputation:
For example I have a constexpr function, but I use a runtime variable (not marked as constexpr
) to take the return value. In this case, I'm not sure whether the function runs on compile time or runtime, So is there any way to debug?
At first I thinked about static_assert
, but it looks like static_assert
cannot do this. Then I thought convert the code to assembly code, but it is way too difficult to check the assembly code to figure out.
Upvotes: 0
Views: 320
Reputation: 25623
Before C++20
there is no way to directly handle it from the program itself.
With C++20
you have std::is_constant_evaluated.
If the return type from your constexpr func is a valid non type template parameter, you can force your function to be evaluated in compile time like this:
constexpr int func( int x )
{
return x*2;
}
template < auto x >
auto force_constexpr_evaluation()
{
return x;
}
int main()
{
int y = force_constexpr_evaluation<func(99)>();
}
If you are using c++20
already, you can directly force compile time evaluation by using consteval
Debugging on assembly level should be not so hard.
BTW: It is not possible to back port std::is_constant_evaluated
to older compilers, as it needs some implementation magic.
Upvotes: 1