Last active
January 28, 2020 20:55
-
-
Save vicro/98a07782c10c4b3cfd4e11857d187997 to your computer and use it in GitHub Desktop.
Getter and Setter example in c++11
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
// Example program | |
#include <iostream> | |
#include <string> | |
/* | |
Getter and setter functor object. | |
T Value type | |
Owner Type of owner class | |
get_function Owner's getter function type | |
set_function Owner's setter function type | |
*/ | |
template<typename T, | |
typename Owner, | |
T (Owner::*get_function)() const, | |
void (Owner::*set_function)(T v)> | |
class GettorSettor | |
{ | |
public: | |
GettorSettor(Owner* owner) | |
: owner_(owner) | |
{} | |
//Get value operator | |
operator T() const | |
{ | |
//Return value of owner's getter function | |
return (owner_->*get_function)(); | |
} | |
//Assign value operator | |
void operator=(T v) | |
{ | |
//Call owner's setter function with parameter | |
(owner_->*set_function)(v); | |
} | |
private: | |
//Pointer to owner instance | |
Owner* owner_; | |
}; | |
class Fulanito | |
{ | |
private: | |
//The backing field | |
uint32_t _myInt_ = 300; | |
//The getter function (not used directly) | |
uint32_t _get_myInt() const { return _myInt_; } | |
//The setter function (not used directly) | |
void _set_myInt(uint32_t v) { _myInt_ = v; } | |
public: | |
Fulanito() | |
: myInt(this) //Initialize GetterSetter with pointer to this instance | |
{} | |
using myInt_t = GettorSettor<uint32_t, Fulanito, &Fulanito::_get_myInt, &Fulanito::_set_myInt>; | |
//Our getter setter for myInt | |
myInt_t myInt; | |
//A traditional setter function (as example) | |
void setInt(uint32_t i) { _myInt_ = i; } | |
}; | |
int main() | |
{ | |
Fulanito f; | |
//try getter to obtain default value | |
std::cout << f.myInt << "\n"; | |
//change value with a normal function | |
f.setInt(999); | |
//value should be reflected with getter | |
std::cout << f.myInt << "\n"; | |
//set value with setter | |
f.myInt = 500; | |
//value should be reflected again | |
std::cout << f.myInt << "\n"; | |
//How to set the value? | |
f.myInt = 10; | |
//How to get the value? | |
uint32_t x = f.myInt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment