Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ////////////////////////////////////////////
- // lazy<T> definition
- ////////////////////////////////////////////
- template<typename T>
- class lazy final {
- lazy() {}
- public:
- class interface {
- public:
- virtual const T & get () const = 0;
- virtual operator const T & () const = 0;
- };
- class proxy: public virtual interface {
- mutable T _value;
- mutable bool _state;
- std::function<void()> _init;
- template<typename ... Types>
- static void Tctor(T* dst, Types ... args) {
- new (dst) T(args ...);
- }
- public:
- template<typename ... Types>
- proxy(Types ... args) {
- _init = std::bind(proxy::Tctor<Types ...>, &_value, args ...);
- _state = false;
- }
- const T & get () const override {
- if (!_state) {
- _init();
- _state = true;
- }
- return _value;
- }
- inline operator const T & () const override {
- return get();
- }
- };
- class func: public virtual interface {
- mutable T _value;
- mutable bool _state;
- std::function<T()> _init;
- public:
- template<typename X>
- func(X init) {
- _init = static_cast<std::function<T()>>(init);
- _state = false;
- }
- const T & get () const override {
- if (!_state) {
- _value = _init();
- _state = true;
- }
- return _value;
- }
- inline operator const T & () const override {
- return get();
- }
- };
- };
- ////////////////////////////////////////////
- // lazy<T> usage example
- ////////////////////////////////////////////
- class oid {
- public:
- //<include>/net-snmp/library/oid.h
- #ifndef EIGHTBIT_SUBIDS
- typedef u_long atom;
- #else
- typedef uint8_t atom;
- #endif
- oid();
- oid(const char * oid_string);
- ~oid();
- size_t length() const;
- const atom* data() const;
- const oid& operator =(const oid& other);
- template<typename T = atom>
- operator T*() const { return reinterpret_cast<T*>(static_cast<atom*>(_ptr)); }
- static constexpr int max_length = 128;
- private:
- boost::shared_array<atom> _ptr;
- size_t _len;
- };
- int main(int argc, char* argv[]) {
- lazy<oid>::proxy system_object_id("1.3.6.1.2.1.1.2.0");
- lazy<oid>::func system_uptime( [] () -> oid { return oid("1.3.6.1.2.1.1.3.0"); } );
- oid x1, x2;
- x1 = system_object_id;
- x2 = system_uptime;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement