I am working on learning c++ and I was wondering if I could pass in a method as a parameter in another method?
A rough outline of what I wanted to do is something like this:
void insertionSort() {
//perform sort
}
int timeOfOperation(methodInQuestion) {
// time 1
methodInQuestion;
//time 2
return time2-time;
}
int main() {
cout << timeOfOperation(insertionSort());
return 0;
}
Is there a way to do something like this?
Edit:
I appreciate the replies. I have another question though. In my actual code, this is all happening in a class called dataStructure and I am creating an instance of it elsewhere and calling these methods.
dataStructure ds();
ds.timeOperation(ds.insertionSort());
When I try to implement some of the solutions posted I am getting this error:
IntelliSense: no instance of function template
"dataStructure::timeOperation" matches the argument list argument
types are: (void) object type is: dataStructure
I’m not really understanding why creating instances would affect this. Can anyone explain?
=============================================================
Edit 2:
I’m going to post more or less my exact code for this portion:
//main.cpp
#include "arrayList.h"
#include "arrayListStructure.h"
#include "Person.h"
using namespace std;
int main() {
arrayList<Person> *al = new arrayList<Person>(length);
arrayListStructure als(al);
//als.fillStructure(data);
als.timeOperation(als.insertionSort());
return 0;
}
//arrayListStructure.cpp
#include "arrayListStructure.h"
#include <functional>
double arrayListStructure::timeOperation(std::function<void()> operation) {...}
void arrayListStructure::insertionSort() {...}
arrayListStructure::arrayListStructure(arrayList<Person> *al)
{
this -> al = al;
}
There is more but I think this is all that relates to the problem
Yes, something like:
Since you probably don’t want global data (which a parameterless function like insertionSort requires), you might do something like:
Now you have to pass the data to be sorted in. You can do this with std::bind or better C++11 lambdas. Then, as noted in Yakk’s answer, we could templatize the timer function so it natively accepts std::functions, lambdas, functors (classes with operator() overloaded), or function pointers:
Here’s the full program:
Combine the last two lines (which use C++11 lambdas) as such:
But of course, in non-homework code, you should use the built-in sort functions rather than rolling your own.
Regarding your update: The first line is actually a function definition, not an instantiation of the class:
In C++ the rule is, if something can be interpreted as a function prototype, it will be. Drop the paretheses and you’ll be fine:
In answer to your comment, as long as it can’t be interpreted as a prototype, you’re good. Consider:
Update for your Edit 2:
Change this line:
to:
or (less preferred, but if you don’t have lambdas):