I have a strange metafunction behavior in my C++ code and I want to understand why.
#include <iostream>
#include <cmath>
inline double f(double x, double y)
{
std::cout<<"Marker"<<std::endl;
return sqrt(x*y);
}
template <int N, class T> inline T metaPow(T x)
{
return ((N > 0) ? (x*metaPow<((N > 0) ? (N-1) : (0))>(x)) : (1.));
}
int main()
{
double x;
double y;
std::cin>>x;
std::cin>>y;
std::cout<<metaPow<5>(f(x, y))<<std::endl;
return 0;
}
I expected that the line metaPow<5>(f(x, y)) was equivalent to f(x, y)*f(x, y)*f(x, y)*f(x, y)*f(x, y)*1.. But if it was, it would print me five times the “Marker” line in the f function.
The strange thing is that I have the good result at the end (for example 181.019 for x = 2 and y = 4) but I have only 1 “Marker” displayed. How is it possible ? And consequently is it a good option to use that function for compile-time optimization instead of the standard pow() ?
Thank you very much !
I believe that
f(x,y)is being evaluated before being passed in to your metaPow function. So the x argument to metaPow is just the value sqrt*(8). metaPow is never calling f(x,y). Hence, f(x,y) is only called once – when you initially call metaPow in your main function.