Can this be solved with templates?

E

Eric Lilja

Hello, I wrote a simple class that can measure the time it takes to
call a function using some platform dependent code. The actual
measurement function in this timer class has this signature:

typedef void (*FunctionPointer)(const long double *, const long double
*, std::size_t);

double TimerClass::time_function(FunctionPointer fptr, const long
double *x, const long double *y, std::size_t size)

The arguments following the function pointer is those that are to be
sent to the function that is measured...so this class is not reusable
at all, it only works for functions taking those arguments...can I do
some template magic here be able to use it with all functions, no
matter their argument lists? Or maybe something else?

- Eric
 
D

dasjotre

Hello, I wrote a simple class that can measure the time it takes to
call a function using some platform dependent code. The actual
measurement function in this timer class has this signature:

typedef void (*FunctionPointer)(const long double *, const long double
*, std::size_t);

double TimerClass::time_function(FunctionPointer fptr, const long
double *x, const long double *y, std::size_t size)

The arguments following the function pointer is those that are to be
sent to the function that is measured...so this class is not reusable
at all, it only works for functions taking those arguments...can I do
some template magic here be able to use it with all functions, no
matter their argument lists? Or maybe something else?

you could use boost::function/bind library

template<class F>
double time_function(F f)
{
// your timing here
f();
}

// 0 arity
void fun();
time_function(&fun);

// 1 arity
void fun1(int);
// time call fun1(5)
time_function(boost::bind(&fun, 5));

// member function
struct A
{
void fun();
void fun1(int);
};

A a;
// time call a.fun()
time_function(boost::bind(&A::fun, &a));

// time call a.fun1(5)
time_function(boost::bind(&A::fun, &a, 5));

D.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,529
Members
48,250
Latest member
Bette22B13

Latest Threads

Top