2

I wonder if it is possible to do this in C ++?

e.g:

varFunction = void TestFunction();
RunCode(varFunction);
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
IEdge
  • 31
  • 5
  • 2
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – cpplearner Jul 08 '17 at 08:22
  • 1
    What you're looking for are [function pointers](http://www.cprogramming.com/tutorial/function-pointers.html). If your functions might also be lambdas, functors or other stateful constructs, [`std::function`](http://de.cppreference.com/w/cpp/utility/functional/function) is the way to go. – Tobias Ribizel Jul 08 '17 at 08:23
  • 3
    Consider reading a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Passer By Jul 08 '17 at 08:23
  • @PasserBy Well, that topic might be covered in the _advanced sections_ of these books. – user0042 Jul 08 '17 at 08:27
  • 1
    @user0042 - Intermediate at most. Advanced features of C++ are slightly more involved then storing a pointer to a function. – StoryTeller - Unslander Monica Jul 08 '17 at 08:29
  • Feel free to mark the good answers as useful and accept the one you think that answered your question. – Akira Jul 10 '17 at 04:30

4 Answers4

5

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.

Akira
  • 4,385
  • 3
  • 24
  • 46
  • Inherited from C, I presume. You can do similar things in C. – Tom Zych Jul 08 '17 at 08:33
  • C don't have yet any notion of lambda expressions or closures (but that might change in the future C20 standard). That requires the compiler to compute the set of closed values (in a lambda). – Basile Starynkevitch Jul 08 '17 at 08:33
3

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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.

Garmekain
  • 664
  • 5
  • 18
0

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

Daniel Illescas
  • 5,346
  • 3
  • 17
  • 23