Hello all,
I have been using C# in my programming class and I have grown quite fond
of C# properties. Having a method act like a variable that I can control
access to is really something. As well as learning C#, I think that it's way
overdue for me to start learning C++ Templates (I've been learning it for
about 5 years now).
I think that adding this type of functionality would be a good exercise
to help learn template programming. But befor I start, does anyone know if
it's even possible to add the functionality of C# properties to C++ using
templates? If so then that is all I need, but if not, can anyone suggest an
easy assignment to help learning template programming? 11 2511
Brent Ritchie wrote: Hello all,
I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. As well as learning C#, I think that it's way overdue for me to start learning C++ Templates (I've been learning it for about 5 years now).
I think that adding this type of functionality would be a good exercise to help learn template programming. But befor I start, does anyone know if it's even possible to add the functionality of C# properties to C++ using templates? If so then that is all I need, but if not, can anyone suggest an easy assignment to help learning template programming?
Hi, this is a very interesting question, and since I very much like the
concept of properties in C# (I generally think it's a very nice
language), I came up with this in C++:
---------- 8< --------------------------
class Foo {
public:
Foo(): X(0), Y(0), Z(0) {}
Property<int, GET> X;
Property<int, SET> Y;
Property<int> Z;
};
int main()
{
Foo f;
int val;
f.X = 5; // error, read only
val = f.X; // OK
f.Y = 5; // OK
val = f.Y; // error, write only
f.Z = 5; // OK
val = f.Z; // OK
}
---------- 8< --------------------------
Below is the code which realizes the Property class. It may still be
dirty in one way or another, it's just what I came up by hacking around:
---------- 8< --------------------------
enum permission { GET, SET, GETSET };
template <typename T, permission perm = GETSET>
class Property {
public:
Property(const T& val): value(val) {}
virtual operator T() { return value; }
protected:
T value;
};
template <typename T>
class Property<T, GET> {
public:
explicit Property(const T& val): value(val) {}
virtual operator T() { return value; }
protected:
T value;
};
template <typename T>
class Property<T, SET> {
public:
Property(const T& val): value(val) {}
protected:
T value;
};
---------- 8< --------------------------
For example, it may be a better idea to realize permissions through
inheritance, I don't know, maybe someone else can come up with something
more pleasing, but at least it already works.
Tell me what you think.
Regards,
Matthias
On Mon, 21 Nov 2005 19:41:11 +0100, Matthias Kaeppler <vo**@void.com>
wrote: For example, it may be a better idea to realize permissions through inheritance, I don't know, maybe someone else can come up with something more pleasing, but at least it already works.
Tell me what you think.
There are some property implementations floating around the internet,
e.g. http://www.open-std.org/jtc1/sc22/wg...2004/n1615.pdf
Best wishes,
Roland Pibinger
Brent Ritchie wrote: Ok, I see the ctor and the selfnamed operator. This is fine and it is very elegant. One question though where is operator= ? I used your implementation and used operator= but it is not here. How does that work exactly?
You could also use operator=. I used the copy constructor, which also
works. If it isn't declared 'explcicit', the compiler may use it to
convert from the parameter type to the class' type. How did you achieve readonly access? Because the ctor is declared explicit?
That's right. An explicit ctor must not be used for implicit type
conversion, so that's fine.
I think I actually understand this for the most part. Except for how did I do:
Property<int> i(3); i == 2;
And not have operator= defined?
You would have to define operator==. My code was just supposed to
outline how one could implement a property, it's nowhere complete.
Here's another Property implementation.
This time I left the whole template thing out completely. It only uses
the preprocessor, and feels way more like C# properties than anything
using templates:
class Outer {
public:
property (MyProp, int) {
self(MyProp, int) {
// init property
}
get(int) {
// do something
return value;
}
set(int) {
// do something
this->value = value;
}
} myProperty, anotherProperty;
};
You can then use it like this:
Outer o;
int val;
o.myProperty = val;
val = o.myProperty;
o.anotherProperty = o.myProperty;
assert (o.myProperty == o.anotherProperty);
This version uses the assignment operator rather than the copy constructor.
#define property(name,type) class name
#define self(name,type) private: type value; \
public: bool operator== (const type &rhs) const \
{ return this->value == rhs; } \
public: name ()
#define get(type) public: operator type ()
#define set(type) public: void operator= (const type &value)
However, complex types shouldn't be stored in a property because copying
will be too expensive. It also can't handle "deep" lookup of pointer
types. To achieve that, you will have to rely on template meta
programming I guess.
Regards,
Matthias
Brent Ritchie wrote: Hello all,
I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something.
What is the advantage of
window.color = blue;
over
window.color(blue);
or even
window.change_color(blue);
Why not always use the function notation instead of having two different
notations depending on whether you decide to treat something as a
"property". I just don't understand the motivation for making a
distinction between changing or requesting "properties" and other forms
of object interaction.
Gregg
"GB" <gb@invalid.invalid> wrote in message
news:wsRgf.7083$0h5.3886@dukeread10... Brent Ritchie wrote: Hello all,
I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. What is the advantage of
window.color = blue;
over
window.color(blue);
or even
window.change_color(blue);
Really, the only difference (to me) is purely cosmetic. Although using
functions is one way of doing it, I would rather use window.color = BLUE
because it is a simple assignment with (probably) very simple error checking
needed.
Why not always use the function notation instead of having two different notations depending on whether you decide to treat something as a "property". I just don't understand the motivation for making a distinction between changing or requesting "properties" and other forms of object interaction.
The driving force behind this is my lazyness and hatred of Accessor/Mutator
pairs. I Like to keep functions that are useful public, and not pollute the
class namespace with nearly useless get/set functions. This way I could hide
the implementation from other programmers who need not know about why
something works just that it does. Also I think properties enforce
encapsulation better. They give a simple interface to hide as many
implementation details as possible.
Gregg
Brent Ritchie wrote: "GB" <gb@invalid.invalid> wrote in message news:wsRgf.7083$0h5.3886@dukeread10... Brent Ritchie wrote: Hello all,
I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. What is the advantage of
window.color = blue;
over
window.color(blue);
or even
window.change_color(blue);
Really, the only difference (to me) is purely cosmetic. Although using functions is one way of doing it, I would rather use window.color = BLUE because it is a simple assignment with (probably) very simple error checking needed.
Probably simple error checking, or perhaps not, the amount of error
checking is irrelevant if you're encapsulating, right? Why not always use the function notation instead of having two different notations depending on whether you decide to treat something as a "property". I just don't understand the motivation for making a distinction between changing or requesting "properties" and other forms of object interaction.
The driving force behind this is my lazyness and hatred of Accessor/Mutator pairs. I Like to keep functions that are useful public, and not pollute the class namespace with nearly useless get/set functions. This way I could hide the implementation from other programmers who need not know about why something works just that it does. Also I think properties enforce encapsulation better. They give a simple interface to hide as many implementation details as possible.
I have to disagree. If it looks like a public variable, people will
expect it to behave like one... should what looks like a simple
assignment throw an exception?
And if you consistantly use the function notation, then you are
simplifying the interface.
Additionally, providing direct access to the members (or appearing to)
doesn't really hide the implementation details.
Having said that:
class Thing {
int property_;
public:
const int& property() const { return property_; }
int& property() { return property_; }
};
class OtherThing {
int property_;
public:
int property() const { return property_; }
void property(int val) { property_ = val; }
};
int main() {
Thing thing;
thing.property() = 4;
int myProperty = thing.property();
OtherThing otherThing;
otherThing.property(4);
int myOtherProperty = otherThing.property();
}
Whats wrong with those two ways of exposing the properties? It's a
pretty simple interface. You don't have to prepend the functions with
get & set, just take advantage of overloading.
Ben Pope
"Ben Pope" <be*****************@gmail.com> wrote in message
news:11*****************************************@f e5.teranews.com... Brent Ritchie wrote: "GB" <gb@invalid.invalid> wrote in message news:wsRgf.7083$0h5.3886@dukeread10... Brent Ritchie wrote: Hello all,
I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. What is the advantage of
window.color = blue;
over
window.color(blue);
or even
window.change_color(blue);
Really, the only difference (to me) is purely cosmetic. Although using functions is one way of doing it, I would rather use window.color = BLUE because it is a simple assignment with (probably) very simple error checking needed.
Probably simple error checking, or perhaps not, the amount of error checking is irrelevant if you're encapsulating, right?
I have to agree. Encapsulation should automatically hide these
implementation details. What I think properties are useful for is not just
an excuse for public variables. What I think properties are useful for is to
create simple to use members that have functionality that makes sense in the
context of thier object. Say I have a Clock object with three members Hours,
Minutes Seconds. Using encapsulation rules I would write out
Accessor/Mutator pairs for each variable. If I wanted to add some value to
Minutes then I would create another function to do that, same with Hours and
Seconds. In these new functions I would again use the accessor/mutator
pairs. I always found that in this context, I always end up with functions
that do normal variable routines but use longer function names. What I
suggest is use a "property" so that they "Look" like public variables but
"Behave" in whichever context they are in. I would rather read:
Clock clock(0, 0, 0);
clock.Minutes += 80;
cout << clock.Hours << " : " << clock.Minutes << endl;
output would read : 1 : 20
This just makes sense for a Clock class to do, and I dont have to keep
typing something like clock.addMinutes(80); It just seems more intuitive to
me like this. Why not always use the function notation instead of having two different notations depending on whether you decide to treat something as a "property". I just don't understand the motivation for making a distinction between changing or requesting "properties" and other forms of object interaction.
The driving force behind this is my lazyness and hatred of Accessor/Mutator pairs. I Like to keep functions that are useful public, and not pollute the class namespace with nearly useless get/set functions. This way I could hide the implementation from other programmers who need not know about why something works just that it does. Also I think properties enforce encapsulation better. They give a simple interface to hide as many implementation details as possible.
I have to disagree. If it looks like a public variable, people will expect it to behave like one... should what looks like a simple assignment throw an exception?
Actually, after using java for a while I've grown quite fond of
everything being able to throw an exception. This allows me to create code
that can dynamically fix any mistakes that may crop up and notify me right
away that there is a problem with one of my classes or methods or whatever.
Being ready for exceptions from anywhere is always a good thing in my mind.
And if you consistantly use the function notation, then you are simplifying the interface.
Simplifying yes, Easier to use, maybe. When creating a class, you have
to watch the length of your member names that you use. If you don't then you
run the risk of losing time writing and rewriting long member names
especially on members that add functionality for private variables as they
are usually used most. I think that if it makes sense then symbols are
better.
Additionally, providing direct access to the members (or appearing to) doesn't really hide the implementation details.
In a way, it does. Take the Clock example again. If I go clock.Seconds++
and clock.Seconds is already equal to 59 then clock.Seconds++ would set
itself to 0 and do clock.Minutes++ at the same time to simulate a real
clock. Someone using this class knows that this happens they just don't have
to know how it actually happens. They are just glad that it does happen with
no effort on their part.
Having said that:
class Thing { int property_; public: const int& property() const { return property_; } int& property() { return property_; } };
class OtherThing { int property_; public: int property() const { return property_; } void property(int val) { property_ = val; } };
int main() { Thing thing; thing.property() = 4; int myProperty = thing.property();
OtherThing otherThing; otherThing.property(4); int myOtherProperty = otherThing.property(); }
Whats wrong with those two ways of exposing the properties? It's a pretty simple interface. You don't have to prepend the functions with get & set, just take advantage of overloading.
Nothing is wrong with any of those, they are valid and easy to read. But
the problem is when you add funtionality what happens whan you want to add
one to your property? you would have to right a function say addProperty(int
val) { property += val; } where as Thing.Property++ or Thing.Property += 1.
is shorter and is still obvious to the user. Also the way you do it, I have
to rewrite the default functionality for each member every time I write a
class. With my template I can have the basic functionality as soon as I
declare it, and extend it as I see fit.
Ben Pope
Brent Ritchie wrote: "Ben Pope" <be*****************@gmail.com> wrote in message And if you consistantly use the function notation, then you are simplifying the interface.
Simplifying yes, Easier to use, maybe. When creating a class, you have to watch the length of your member names that you use. If you don't then you run the risk of losing time writing and rewriting long member names especially on members that add functionality for private variables as they are usually used most. I think that if it makes sense then symbols are better.
OK, I'm not with you:
class Thing {
private:
int minutes_;
int hours_;
public:
int& minutes();
int& hours();
};
Member names for accessors are the same (except the underscore) as the
private member variable. Additionally, providing direct access to the members (or appearing to) doesn't really hide the implementation details.
In a way, it does. Take the Clock example again. If I go clock.Seconds++ and clock.Seconds is already equal to 59 then clock.Seconds++ would set itself to 0 and do clock.Minutes++ at the same time to simulate a real clock. Someone using this class knows that this happens they just don't have to know how it actually happens. They are just glad that it does happen with no effort on their part.
Having said that:
class Thing { int property_; public: const int& property() const { return property_; } int& property() { return property_; } };
int main() { Thing thing; thing.property() = 4; int myProperty = thing.property(); }
Whats wrong with those two ways of exposing the properties? It's a pretty simple interface. You don't have to prepend the functions with get & set, just take advantage of overloading.
Nothing is wrong with any of those, they are valid and easy to read. But the problem is when you add funtionality what happens whan you want to add one to your property? you would have to right a function say addProperty(int val) { property += val; } where as Thing.Property++ or Thing.Property += 1. is shorter and is still obvious to the user.
No you don't; from my trimmed example above:
thing.property() += 4;
Perfectly valid code.
Also the way you do it, I have to rewrite the default functionality for each member every time I write a class. With my template I can have the basic functionality as soon as I declare it, and extend it as I see fit.
That's pretty lazy. There shouldn't be that many times you want to
provide direct access to the members, and when you do, you'll want to
minimise access as much as possible, which will require writing a small
amount of code.
Ben Pope
"Ben Pope" <be*****************@gmail.com> wrote in message
news:11*****************************************@f e5.teranews.com... Brent Ritchie wrote: "Ben Pope" <be*****************@gmail.com> wrote in message And if you consistantly use the function notation, then you are simplifying the interface.
Simplifying yes, Easier to use, maybe. When creating a class, you have to watch the length of your member names that you use. If you don't then you run the risk of losing time writing and rewriting long member names especially on members that add functionality for private variables as they are usually used most. I think that if it makes sense then symbols are better.
OK, I'm not with you:
class Thing { private: int minutes_; int hours_; public: int& minutes(); int& hours(); };
Member names for accessors are the same (except the underscore) as the private member variable.
Yes, thats true but it's not what develoopers are used to. This is not
intuitive to a developer who does not understand your programming style and
does not have the time to give your documentation more then a passing glance
to get the gist of it. When they import your package they can't read your
source to see exactly what you have done because it has been compiled.
My strongest argument for properties is that they are indeed intuitive
and respond like normal member variables to common operations. The only
difference is they have hard constraints that can be changed however you
like. With your implementation you have to derive a new class and override
every mechanism that need tighter constraints. Granted you can use function
pointers but this forces that type of management on to any programmer that
decides to use this type of mechanism. Using a template everything is done
for you and you don't need to woory about the error prone management of
function pointers.
The way you access the features of a class is every bit as important as
the features themselves. More often then not you will never be the only
programmer using these classes, and just as often these classes will span
multiple projects. Now, I don't know if your a professional developer, but I
thought I should remind everyone that this is true in businesses of any
size. I have never worked in industry myself but I do know people in it and
I have learned much from them. People always complain if something makes
their job harder especially when they need the functionality of a specific
package. Additionally, providing direct access to the members (or appearing to) doesn't really hide the implementation details.
In a way, it does. Take the Clock example again. If I go clock.Seconds++ and clock.Seconds is already equal to 59 then clock.Seconds++ would set itself to 0 and do clock.Minutes++ at the same time to simulate a real clock. Someone using this class knows that this happens they just don't have to know how it actually happens. They are just glad that it does happen with no effort on their part.
Having said that:
class Thing { int property_; public: const int& property() const { return property_; } int& property() { return property_; } };
int main() { Thing thing; thing.property() = 4; int myProperty = thing.property(); }
Whats wrong with those two ways of exposing the properties? It's a pretty simple interface. You don't have to prepend the functions with get & set, just take advantage of overloading.
Nothing is wrong with any of those, they are valid and easy to read. But the problem is when you add funtionality what happens whan you want to add one to your property? you would have to right a function say addProperty(int val) { property += val; } where as Thing.Property++ or Thing.Property += 1. is shorter and is still obvious to the user.
No you don't; from my trimmed example above:
thing.property() += 4;
Perfectly valid code.
Also the way you do it, I have to rewrite the default functionality for each member every time I write a class. With my template I can have the basic functionality as soon as I declare it, and extend it as I see fit.
That's pretty lazy. There shouldn't be that many times you want to provide direct access to the members, and when you do, you'll want to minimise access as much as possible, which will require writing a small amount of code.
You can call it lazy, I call it economical. If you have a class that is
meant as a datastore and has an internal state of say 20 variables, 8 need
direct access and say 5 need some type of restricted access. This is at a
minimum 21 new members to implement this wil not take a non-trivial amount
of time. It would probably take a nice chunk of an hour. Then they all have
to be tested, which will take more time. Using some type of already tested
mechanism such as properties would greatly reduce this time and is much less
error prone.
Granted it's probably not often you need a datastore but over time every
minute you spend coding is about 10 seconds of testing. The less coding you
do the fewer tests you run, the more real work you can do. Code reuse,
(Where it makes sense) is always a best practice, this means shorter
development times and higher quality software.
This stuff is probably not new but it is fundamental to why I think
properties are better then roll-your-own Accessor/Mutator functions. Already
tested, extendable, common default implementations and intuitive use.
Ben Pope
That's a great paper - some rational thought on the whole idea behind
"properties" This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: nanookfan |
last post by:
Hi all,
I'm having a bizarre problem converting XML files to HTML using an
XSLT. The problem is only occuring in my Netscape 7.0 browser. What
makes it more bizarre is that it is only...
|
by: Alex Sab |
last post by:
Hi,
I am having trouble describing in a schema that elements can be
mandatory in one part and not mandatory in another part of the xml
document. Here is a sample xml file
<Model:Templates>...
|
by: Jon Slaughter |
last post by:
Lets assume I want to write a whole host of classes having "property"
elements in them and create a bunch of objects from the different classes.
Lets suppose that they are circles, lines, etc......
|
by: Mark Miller |
last post by:
I have a scheduled job that uses different XSL templates to transform XML
and save it to disk. I am having problems with the code below. The problem
shows up on both my development machine (Windows...
|
by: Jon Hyland |
last post by:
This might be a dumb question, but what is the best way for one
instance of a user control to access properties of an instance of
another user control?
For example, let's say I have an instance...
|
by: Rene |
last post by:
We all know that we can't call custom methods or properties form generic
type parameters (<T>) by default because the compiler will complain about
his. For example, the following won't normally...
|
by: NewToCPP |
last post by:
Hi,
I am just trying to find out if there is any strong reason for not
using Templates. When we use Templates it is going to replicate the
code for different data types, thus increasing the...
|
by: Michael Matteson |
last post by:
I have two classes. Class
A and Class B. I give class A 5 properties
int prop1(){}
int prop2(){}
int prop3(){}
int prop4(){}
classB prop5(){}
what i would like to do is to create a 5th...
|
by: Andrus |
last post by:
I'm using VCS Express 2005.
I have a lot of property definitions in different classes like
public class MyEntity {
public string somestringfield {
get { return (string)Row; }
set { Row =...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
| | |