0

我的 C++ 代码中有一个奇怪的元函数行为,我想了解原因。

#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;
}

我预计这条线metaPow<5>(f(x, y))相当于f(x, y)*f(x, y)*f(x, y)*f(x, y)*f(x, y)*1.. 但如果是,它会在函数中打印五次“ Marker”行。f

奇怪的是,我最后得到了很好的结果(例如181.019forx = 2y = 4),但我只Marker显示了 1 个 " " 。这怎么可能 ?因此,使用该函数而不是标准 pow() 进行编译时优化是一个不错的选择吗?

非常感谢你 !

4

2 回答 2

5

我相信f(x,y)在传递给您的 metaPow 函数之前正在对其进行评估。所以 metaPow 的 x 参数就是 sqrt*(8) 的值。metaPow 从不调用 f(x,y)。因此, f(x,y) 仅被调用一次 - 当您最初在主函数中调用 metaPow 时。

于 2012-05-08T03:48:56.917 回答
2

我认为:

metaPow<5>(f(x, y))

等于

双 z = f(x, y); metaPow<5>(z);

于 2012-05-08T03:54:43.447 回答