简体   繁体   English

如何设置函数指针参数,使其接受任何内容

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

I'm looking for a way to pass function A() as an argument to function B() in order to calculate the running time of A(). 我正在寻找一种方法将函数A()作为函数B()的参数传递,以便计算A()的运行时间。

For example: 例如:

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

My problem is that I have many different functions to test (that does the same job) with different return types and different signatures. 我的问题是我有许多不同的函数来测试(做同样的工作)具有不同的返回类型和不同的签名。 I do not know how to correctly set up the field of the previous example as I'm getting conversion errors. 因为我收到转换错误,我不知道如何正确设置上一个示例的字段。

You can use templates: 您可以使用模板:

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

   a();

   ...
}

This is very simple. 这很简单。

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

One solution is wrap your function in a functor and use an instance of the functor to call the timer. 一种解决方案是将函数包装在仿函数中,并使用仿函数的实例来调用计时器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM