Last active
August 29, 2015 13:57
-
-
Save zschoche/9509087 to your computer and use it in GitHub Desktop.
Get rid of writing getters and setters.
This file contains 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
#ifndef __Z_MUTATOR_HPP__ | |
#define __Z_MUTATOR_HPP__ | |
#include <utility> | |
#include <iostream> | |
namespace mutator { | |
template <typename T> struct ref { | |
template <typename... Args> | |
ref(Args &&... args) | |
: m_item(std::forward<Args>(args)...) {} | |
ref &operator=(const ref &) = delete; | |
ref &operator=(ref &&) = delete; | |
inline const T &operator()() const { return m_item; } | |
template <typename S> void operator()(S &&item) { | |
m_item = std::forward<S>(item); | |
} | |
private: | |
T m_item; | |
}; | |
template <typename T> struct copy { | |
template <typename... Args> | |
copy(Args &&... args) | |
: m_item(std::forward<Args>(args)...) {} | |
copy &operator=(const copy &) = delete; | |
copy &operator=(copy &&) = delete; | |
inline T operator()() const { return m_item; } | |
template <typename S> void operator()(S &&item) { | |
m_item = std::forward<S>(item); | |
} | |
private: | |
T m_item; | |
}; | |
} | |
#endif | |
// how to use | |
struct object { | |
mutator::copy<int> number; | |
mutator::ref<std::string> text; | |
}; | |
int main() { | |
object obj; | |
obj.number(42); | |
obj.text("foo"); | |
std::cout << obj.text() << obj.number() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment