Skip to content

Instantly share code, notes, and snippets.

@jdee
Last active June 28, 2019 17:34
Show Gist options
  • Save jdee/5fa43f225d21e2041106f9567b12656d to your computer and use it in GitHub Desktop.
Save jdee/5fa43f225d21e2041106f9567b12656d to your computer and use it in GitHub Desktop.
passing a writable method
#include <exception>
#include <iostream>
#include <string>
using namespace std;
struct GetterOfThings
{
virtual ~GetterOfThings() {}
virtual string& getWritableName() = 0;
};
struct ThingUpdater
{
static void update(GetterOfThings& getter, const string& updatedName)
{
getter.getWritableName() = updatedName;
}
};
class Thing : protected virtual GetterOfThings
{
public:
Thing(const string& name = string()) : m_name(name) {}
const string& getName() const { return m_name; }
void update()
{
ThingUpdater::update(*this, "updated name");
}
protected:
string& getWritableName() { return m_name; }
// This prevents the compiler from picking up the public method
// string& getName() { return m_name; }
private:
string m_name;
};
int
main(int arc, char** argv)
{
try
{
Thing thing;
cout << "name = " << thing.getName() << endl;
cout << "updating" << endl;
thing.update();
cout << "name = " << thing.getName() << endl;
return 0;
}
catch (const exception& e)
{
cerr << "exception in main: " << e.what() << endl;
}
catch (...)
{
cerr << "unexpected exception in main" << endl;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment