Skip to content

Instantly share code, notes, and snippets.

@santa4nt
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santa4nt/00eedf2cda79945c3f0a to your computer and use it in GitHub Desktop.
Save santa4nt/00eedf2cda79945c3f0a to your computer and use it in GitHub Desktop.
A sample usage of (template) function taking a "callable" as argument.
#include <functional>
#include <iostream>
#include <string>
using namespace std;
// define a templated function to be able to take any "callable" as argument
template<typename Func>
void foo(Func func)
{
string input("foo");
func(input); // just call the argument `func`
}
static void f(const string &input)
{
cout << "f: " << input << endl;
}
class G
{
public:
void operator()(const string &input)
{
cout << "G: " << input << endl;
}
};
int main()
{
// using a function pointer ...
void (*fp)(const string&) = &f; // optional
foo(fp); // or, foo(&f)
// using a functor ...
G g;
foo(g);
// or ...
foo(G());
// using a lambda ...
function<void(const string&)> /* auto */ l = [](const string& input) -> void
{
cout << "lambda: " << input << endl;
};
foo(l);
// or ...
foo([](const string& input) -> void
{
cout << "lambda: " << input << endl;
});
}
/**
* Output:
*
* f: foo
* G: foo
* G: foo
* lambda: foo
* lambda: foo
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment