|
Boost : |
Subject: [boost] Read only attributes in C++ (class proposal)
From: Daniel Illescas Romero (elamericano_at_[hidden])
Date: 2016-10-17 05:36:47
Hello, I wanted to make some read only attributes on C++ so I made a class, named ReadOnly. This class will contain an internal private value, only âfriendâ classes could change this internally.
Description:
· A read only object will contains an internal value that canât be changed outside the class. For example: ReadOnly<string> name = âDanielâ;
To access its value: object.name, if you try: object.name = âotherâ, it wonât change itâs value because itâs a read only variable; you can change itâs value only inside the class the object is declared, you could change it like: name.value = âwhateverâ;
· To set a value (outside the class) to a read only attribute you MUST specify a setter function (which can be static and contained inside the class), like:
ReadOnly<int> age {ReadOnly::setAge, 1}; (optionally you can also set a default value to the attribute).
Example of setter function:
static bool setAge(const int& value) {
return (value > 0 && value <= 150);
}
So if you you have an object and you want to change its value like this: object.age = 100; it will change its internal value only if the setter function (which is called internally) returns true.
· The idea of doing all of this instead private variables and getters & setters is because this approach is closer to OOP than what is normally used; I mean if you have an object and you want to get an attribute value, what you need to do in most cases is something like: object.getAttribute(), you are calling a function to just take a look at an attribute, that shouldnât make sense in OOP, thatâs why I made all of this.
Itâs also similar to how you manage getters and setters in Swift, because they are embedded in the attribute and you donât need to make other functions. :)
I uploaded the project to github so everyone can take a look: https://github.com/illescasDaniel/ReadOnly <https://github.com/illescasDaniel/ReadOnly>
â
I wanted to know your opinion about the idea of the class and also about the implementation, Iâd love to upload it to boost libraries but I want to know people opinion and make the class better.
Thank you!
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk