Created
February 2, 2014 11:31
-
-
Save C0deH4cker/8767019 to your computer and use it in GitHub Desktop.
C# style properties in C++
This file contains hidden or 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
// | |
// Property.h | |
// | |
// Created by C0deH4cker on 2/2/14. | |
// Copyright (c) 2014 C0deH4cker. All rights reserved. | |
// | |
#ifndef _PROPERTY_H_ | |
#define _PROPERTY_H_ | |
#include <functional> | |
#define getter [&] | |
#define setter [&] | |
template <typename T> | |
class Property { | |
private: | |
std::function<T()> _getter; | |
std::function<void(const T&)> _setter; | |
public: | |
Property(std::function<T()> _getter, std::function<void(const T&)> _setter=[](const T&){}) | |
: _getter(_getter), _setter(_setter) {} | |
// Getter | |
operator T() { | |
return _getter(); | |
} | |
// Setter | |
Property<T>& operator=(const T& value) { | |
_setter(value); | |
return *this; | |
} | |
T& operator*() { | |
return *_getter(); | |
} | |
T& operator->() { | |
return *_getter(); | |
} | |
const T& operator()() { | |
return _getter(); | |
} | |
}; | |
#endif /* _PROPERTY_H_ */ |
This file contains hidden or 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
// | |
// proptest.cpp | |
// | |
// Created by C0deH4cker on 2/2/14. | |
// Copyright (c) 2014 C0deH4cker. All rights reserved. | |
// | |
#include <iostream> | |
#include <cmath> | |
#include "Property.h" | |
class Vector2 { | |
private: | |
float _x, _y; | |
public: | |
Vector2(float x, float y) | |
: _x(x), _y(y) {} | |
Property<float> x { | |
getter { | |
return _x; | |
}, | |
setter(float value) { | |
_x = value; | |
} | |
}; | |
Property<float> y { | |
getter { | |
return _y; | |
}, | |
setter(float value) { | |
_y = value; | |
} | |
}; | |
Property<float> magnitude { | |
getter { | |
return sqrtf(_x*_x + _y*_y); | |
} | |
}; | |
}; | |
int main(int argc, char* argv[]) { | |
Vector2 pos(2.0f, -7.91f); | |
std::cout << "pos: (" << pos.x << ", " << pos.y << ")" << std::endl; | |
pos.x = 5.91f; | |
pos.y = 2.88f; | |
std::cout << "pos: (" << pos.x << ", " << pos.y << ")" << std::endl; | |
std::cout << "Magnitude = " << pos.magnitude << std::endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment