Consider the following code, which is contained in a library of my making.
#include <complex>
std::complex<double> besselJ(int order, std::complex<double> z)
{
// Function call
}
std::complex<double> besselH1(int order, std::complex<double> z)
{
// Function call
}
Notice that both functions have the same signature. Now, I want to write a third function that does exactly the same thing whether it's acting on besselJ
or besselH1
. I tried the following
template<std::complex<double> (*T)(int, std::complex<double>)>
std::complex<double> diffBessel(int order, std::complex<double> z)
{
return T(order-1, z)-T(order+1,z);
}
When a member function tries to use the syntax diffbessel<besselJ>(int, std::complex<double>
, GCC complains that the value of 'besselJ' is not usable in a constant expression
. See this answer for an explanation.
Is there a way to do something like the templated code above would do if it worked without resorting to wrapping besselJ
and besselH1
in struct
s? I think structs would add unneeded complexity.
UPDATE: This works beautifully, as @aschepler suggested it should. There was a name collision in the actual code. It took that extra 1001th look to see it. I had been confused by other StackOverflow articles which suggested that this wouldn't work because the function pointer was mutable.