C# properties using C++ Templates, is it Possible?

B

Brent Ritchie

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?
 
M

Matthias Kaeppler

Brent said:
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
 
B

Brent Ritchie

Matthias Kaeppler said:
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 };

I am hardly thrilled about the enumeration, but I see why you used it.
It does make things alot easier.
template <typename T, permission perm = GETSET>
class Property {
public:
Property(const T& val): value(val) {}
virtual operator T() { return value; }
protected:
T value;
};

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?
template <typename T>
class Property<T, GET> {
public:
explicit Property(const T& val): value(val) {}
virtual operator T() { return value; }
protected:
T value;
};

How did you achieve readonly access? Because the ctor is declared
explicit?
template <typename T>
class Property<T, SET> {
public:
Property(const T& val): value(val) {}
protected:
T value;
};

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?

Like I said, I am new to template programming. Now I see how properties
could be implemented with C++. Now I want to try to create a derivative that
can have the () and operator= methods deferred (Fuction pointers) so that
Acces can be further restricted.

Thanks for the sample code although a little confusing I think I understand
most of it.
 
M

Matthias Kaeppler

Brent said:
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.
 
M

Matthias Kaeppler

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
 
G

GB

Brent said:
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
 
B

Brent Ritchie

GB said:
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.
 
B

Ben Pope

Brent said:
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?
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
 
B

Brent Ritchie

Ben Pope said:
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.
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.
 
B

Ben Pope

Brent said:
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.
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.


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
 
B

Brent Ritchie

Ben Pope said:
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.
No you don't; from my trimmed example above:

thing.property() += 4;

Perfectly valid code.


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.
 
M

Michael O'Keeffe

That's a great paper - some rational thought on the whole idea behind
"properties"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top