Last active
August 29, 2015 14:15
-
-
Save santa4nt/00eedf2cda79945c3f0a to your computer and use it in GitHub Desktop.
A sample usage of (template) function taking a "callable" as argument.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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