Skip to content

Instantly share code, notes, and snippets.

@tomthorogood
Created September 12, 2012 13:52
Show Gist options
  • Select an option

  • Save tomthorogood/3706745 to your computer and use it in GitHub Desktop.

Select an option

Save tomthorogood/3706745 to your computer and use it in GitHub Desktop.
Dynamic function members in C++
#include <string>
#include <iostream>
using namespace std;
typedef string (*callback)(string);
string cb1 (string str)
{
return str + "...in bed!";
}
string cb2 (string str)
{
return str + " ...that's what she said!";
}
class Tester
{
string (*exec)(string);
public:
Tester()
{
}
void setExec(callback cb)
{
exec = cb;
}
string run(string str)
{
return exec(str);
}
};
int main()
{
string foo = "Last night I ate brains.";
Tester tester;
tester.setExec(&cb1);
cout << tester.run(foo) << endl;
tester.setExec(&cb2);
cout << tester.run(foo) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment