Is it possible to compute the square root of an integer with a metafunction with the following signature :
template<unsigned int N> inline double sqrt();
(or maybe using the constexpr keyword, I don’t know what is the best).
With that, sqrt<2>() would be replaced by 1.414... at compile-time.
What would be the best implementation for a such function ?
This may not be what you are looking for, but I wanted to make sure you realized that typically with optimization the compiler will calculate the result at compile time anyway. For example, if you have this code:
With g++ 4.6.3 with optimization -O2, the resulting assembly code is:
The sqrt function is never actually called, and the value is just stored as part of the program.
Therefore to create a function that technically meets your requirements, you simply would need: