Skip to content

Instantly share code, notes, and snippets.

@victorholt
Created August 23, 2016 15:34
Show Gist options
  • Save victorholt/2d8311865a4110c5cb974e6cc3806672 to your computer and use it in GitHub Desktop.
Save victorholt/2d8311865a4110c5cb974e6cc3806672 to your computer and use it in GitHub Desktop.
Store C++ Functions inside of a Class
/************************************
* Example of storing functions inside
* of a class.
*
* Tested with C++14
************************************/
#include <iostream>
#include <vector>
#include <functional>
class MyFunctions
{
public:
typedef std::function<void()> callback_;
/**
* Adds a callback_ to our function array.
*/
inline void AddFunction(callback_ funcCallback)
{
functs_.push_back(funcCallback);
}
/**
* Goes through our functions array and runs
* the stored function.
*/
inline void RunFunctions()
{
for (auto& functEntry : functs_)
{
functEntry();
}
}
/**
* Example of a class function that will
* be stored.
*/
inline void TestFunction()
{
std::cout << "MyFunctions::TestFunction Called" << std::endl;
}
protected:
// Our array of callback functions.
std::vector<callback_> functs_;
};
/**
* Example of a global function.
*/
void TestFunction2()
{
std::cout << "Global TestFunction2 Function Called" << std::endl;
}
int main() {
MyFunctions mF;
mF.AddFunction(std::bind(&MyFunctions::TestFunction, &mF));
mF.AddFunction(std::bind(TestFunction2));
mF.RunFunctions();
return 0;
}
// Output:
// MyFunctions::TestFunction Called
// Global TestFunction2 Function Called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment