I wonder if it is possible to do this in C ++?
e.g:
varFunction = void TestFunction();
RunCode(varFunction);
I wonder if it is possible to do this in C ++?
e.g:
varFunction = void TestFunction();
RunCode(varFunction);
With C++11 and higher, you can use the std::function
to store function pointers and function objects.
But storing function pointers was available in C++ from the start. This means you can store the address of a function and call it later.
BTW, lambda expressions are also very useful (and the closure they are denoting could be assigned or passed as std::function
-s)
Here is an example showing three different ways to achieve what did you asked for:
#include <iostream>
#include <functional>
void RunCode(const std::function<void()>& callable) {
callable();
}
void TestFunction() {
std::cout << "TestFunction is called..." << std::endl;
}
int main() {
std::function<void()> varFunction_1 = TestFunction;
void (*varFunction_2)() = TestFunction;
RunCode(varFunction_1);
RunCode(varFunction_2);
RunCode([]() { std::cout << "TestLambda is called..." << std::endl; });
return 0;
}
But this is just the tip of the iceberg, passing function pointers and function objects as parameters is very common in the algorithms library.
C++ provides several ways to do it.
For example, you can use std::function
template: include <functional>
and use the following syntax (demo):
std::function<void()> varFunction(TestFunction);
varFunction();
You can also use function pointers (Q&A on the topic).
For the sake of completeness, you can declare a C-style function type as follows:
typedef int (*inttoint)(int);
This creates a type inttoint
that can store any function that takes an int as parameter and returns an int. You can use it as follows.
// Define a function
int square(int x) { return x*x; }
// Save the function in sq variable
inttoint sq { square };
// Execute the function
sq(4);
Since C++11, these variables can also store lambda functions, like so
inttoint half { [](int x) { return x/2; } };
And use it same as above.
The easiest way is to use a lambda expression like this:
auto add = [](int a, int b) { return a+b; };
cout << add(10, 20) << endl; // Output: 30
More info about how lambda expressions work: http://en.cppreference.com/w/cpp/language/lambda