Last active
April 25, 2020 23:16
-
-
Save wtrsltnk/5d9e2cd45e30936f088c09ebbef97fbd to your computer and use it in GitHub Desktop.
C# Property in C++
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
#include <functional> | |
#include <iostream> | |
#include <string> | |
template<class T> | |
class Property | |
{ | |
T _value; | |
std::function<T (void)> _get; | |
std::function<void(const T&)> _set; | |
public: | |
Property() | |
{ } | |
Property( | |
std::function<T (void)> get, | |
std::function<void(const T&)> set) | |
: _get(get), | |
_set(set) | |
{ } | |
Property( | |
std::function<T (void)> get) | |
: _get(get) | |
{ } | |
operator T () const | |
{ | |
if (_get) | |
{ | |
return _get(); | |
} | |
return _value; | |
} | |
void operator = (const T& value) | |
{ | |
if (_set) | |
{ | |
_set(value); | |
} | |
else | |
{ | |
_value = value; | |
} | |
} | |
}; | |
class Test | |
{ | |
private: | |
std::string _label; | |
public: | |
Test(); | |
Property<std::string> Label = Property<std::string> | |
( | |
[this]()-> std::string | |
{ | |
return this->_label; | |
}, | |
[this](const std::string& value) | |
{ | |
this->_label = value; | |
} | |
); | |
Property<unsigned int> LabelSize; | |
Property<std::string> Description; | |
}; | |
Test::Test() | |
{ | |
LabelSize = Property<unsigned int> | |
( | |
[this]()-> unsigned int | |
{ | |
return this->_label.size(); | |
} | |
); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
Test test; | |
test.Label = "std functional"; | |
test.Description = "Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members."; | |
std::cout << "label = " << std::string(test.Label) << std::endl | |
<< "label size = " << int(test.LabelSize) << std::endl | |
<< "description = " << std::string(test.Description) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment