I want to do exactly what the title says. I have some third party code with an API.
The information needed to evaluate the function should all be available at compile time to evaluate the function. However it does not appear the third party labeled it constexpr
sadly. Furthermore, I don't have the source code for the full implementation, just headers for a lot of it. It seems it may use a shared object to evaluate the calls as a lot of things seem to be marked extern after drilling down into the API's header files. Due to these calls not being constexpr
every time I try to invoke it for use in static_assert()
compilation fails.
How can I make this function run at compile time and use the result in my constexpr
function to resolve the static_assert()
condition? All the inputs are known at compile time. No external data should be needed.
CodePudding user response:
First of all a function can only be called in a constant expression if its definition is available in the translation unit with the constant expression. That means that if the function definitions are not inline in the header, then it is impossible to call the function in a constant expression at all.
If the function definitions are available inline in the header, then it is still impossible without modifying the header and adding constexpr
.
If you can't recompile the whole library with the modified header, then you'll just have to hope that the ODR violations don't break anything, but that is undefined behavior territory and no guarantee that there won't be subtle bugs resulting from this.
Alternatively you could copy the code from the header file to re-implement all of the functions you want to have constexpr
as constexpr
functions in your own namespace and use these instead. If they are member functions of a class you would however get problems since you would need to re-implement the class as well and probably add a translation layer between the original and new class.
Of course the only proper solution is to ask the supplier of the library to make the relevant functions constexpr
-friendly and supply a new version of the library with those changes implemented.