如何设置一个函数指针参数,以便它接受任何东西
How to set up a function pointer parameter so it accepts anything
我正在寻找一种方法来传递函数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;
}
相关文章:
- 用于检查值是否为其任何参数的帮助程序函数
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- boost::p rogram_options 在指定意外的位置参数时不报告任何错误
- 使用聚合初始化模拟默认函数参数是否存在任何陷阱?
- 在将匿名对象作为参数传递时,不会调用任何构造函数
- 此函数如何在不传递任何参数的情况下工作?
- 高效的可变参数等于任何函数
- 如何声明一个接受任何大小的 2D 矢量参数?
- 如何在C++中接收任何类型的函数参数并获取函数内传递变量的类型?
- 在参数相关查找之前进行模板替换的任何方法(或解决方法?
- 部分专用化不使用其任何模板参数
- 创建一个构造函数,即Capabe获取任何数量的参数
- C++任何非类型参数的模板专用化
- 将字符串(或任何其他参数)传递到QWidget构造函数
- 使用 boost::bind 但允许传递任何其他参数
- 当部分专用化参数不使用其任何模板参数时,哪些规则适用
- 如何使用信号来执行任何带参数的函数
- 通过IDispatch公开COM函数的服务器如何区分调用函数而不传递任何ID参数的不同客户端?