如何设置一个函数指针参数,以便它接受任何东西

How to set up a function pointer parameter so it accepts anything

本文关键字:任何东 参数 函数 设置 何设置 一个 指针      更新时间:2023-10-16

我正在寻找一种方法来传递函数a()作为函数B()的参数,以计算a()的运行时间。

例如:

double timer(<passing function A>) {
    clock_t before = clock();
    <calling function A - not caring about what it returns>;
    clock_t after = clock();
    return (double) (before - after) / (double) CLOCKS_PER_SEC;
}

我的问题是,我有许多不同的函数测试(做同样的工作)不同的返回类型和不同的签名。我不知道如何正确设置前一个例子的字段,因为我得到转换错误。

你可以使用模板:

template <typename A>
double timer(const A a) {
   ...
   a();
   ...
}

这很简单。

template< class Func >
auto timer( Func const a )
    -> double
{
    // ...
}

一种解决方案是将函数包装在一个函子中,并使用该函子的一个实例来调用计时器。

template <typename F>
double timer(F f) {
    clock_t before = clock();
    f();
    clock_t after = clock();
    return (double) (before - after) / (double) CLOCKS_PER_SEC;
}
int foo(double a)
{
   return (int)(a*a);
}
// foo cannot be used directly as a parameter to timer.
// Construct a functor that wraps around foo.
// An object of FooFunctor can be used as a parameter to timer.
struct FooFunctor
{
   FooFunctor(double a) : a_(a) {}
   void operator(){res_ = foo(a_);}
   double a_;
   int res_;
};
bool bar(double a, double b)
{
   return (a<b);
}
// Similar to foo and FooFunctor.
// Construct a functor that wraps around bar.
// An object of BarFunctor can be used as a parameter to timer.    
struct BarFunctor
{
   BarFunctor(double a, double b) : a_(a), b_(b) {}
   void operator(){res_ = foo(a_, b_);}
   double a_;
   double b_;
   bool res_;
};
void test()
{
   FooFunctor f(10.0);
   std::cout << "Time taken: " << timer(f) << std::endl;
   BarFunctor b(10.0, 20,0);
   std::cout << "Time taken: " << timer(b) << std::endl;
}