Skip to content

Instantly share code, notes, and snippets.

@vinipsmaker
Created August 16, 2013 19:16
Show Gist options
  • Save vinipsmaker/6252706 to your computer and use it in GitHub Desktop.
Save vinipsmaker/6252706 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
namespace dyn
{
namespace impl
{
template<class T>
struct mutator
{
virtual T operator()() = 0;
virtual void operator()(const T &) = 0;
};
template<class T>
class basic_mutator: public mutator<T>
{
public:
basic_mutator(T value) : value(value) {}
T operator()() override
{
return value;
}
void operator()(const T &value) override
{
this->value = value;
}
private:
T value;
};
}
struct some_base {};
template<class T>
class mutator: public some_base
{
public:
mutator(std::shared_ptr<impl::mutator<T>> mutator) :
real(mutator)
{
}
T operator()()
{
return (*real)();
}
void operator()(const T &value)
{
(*real)(value);
}
private:
std::shared_ptr<impl::mutator<T>> real;
};
inline mutator<int> callable(int value)
{
return mutator<int>(std::make_shared<impl::basic_mutator<int>>(value));
}
}
int main()
{
int value = 42;
std::cout << "1> " << value << std::endl;
dyn::mutator<int> mutator = dyn::callable(value);
std::cout << "2> " << mutator() << std::endl;
mutator(2520);
std::cout << "3> " << mutator() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment