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 2546
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.co m>
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.anotherProper ty = o.myProperty;
assert (o.myProperty == o.anotherProper ty);
This version uses the assignment operator rather than the copy constructor.
#define property(name,t ype) 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(bl ue);
or even
window.change_c olor(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.inv alid> wrote in message
news:wsRgf.7083 $0h5.3886@duker ead10... 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(bl ue);
or even
window.change_c olor(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.inv alid> wrote in message news:wsRgf.7083 $0h5.3886@duker ead10... 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(bl ue);
or even
window.change_c olor(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.prop erty(4);
int myOtherProperty = otherThing.prop erty();
}
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******** *************** *************** ***@fe5.teranew s.com... Brent Ritchie wrote: "GB" <gb@invalid.inv alid> wrote in message news:wsRgf.7083 $0h5.3886@duker ead10... 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(bl ue);
or even
window.change_c olor(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.addMinute s(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.prop erty(4); int myOtherProperty = otherThing.prop erty(); }
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 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 happening when I put my XML
files and the .xsl files on my ISP's system for my home page. If I
try to open the XML files in Netscape 7.0 on my own machine (ie, not
on the ISP's system), the pages convert file and the result is
displayed in HTML.
|
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>
<Node:Template Node:nodeId="nodeID">
<Node:Name Node:Comment="">Name</Node:Name>
<Node:Name2 Node:Comment="">Name</Node:Name2>
...
|
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... and I display them on the
screen for the user. Now I want to have a window that allows the user to
modify all the "properties" of the object.
It is very similar in how VS.net has a window pane that lets you modify the
different default values of...
|
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 XP Pro SP 1, .Net Framework
1.1) and on our production server (Windows 2K SP 4, .Net Framework 1.1). I
have simplified the code and data to isolate the problem. When I use the
xsl:strip-space (Line 12) declaration in conjunction with the xsl:sort...
|
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 of UserControlA (ucA1) and
an instance of UserControlB (ucB1) on a particular ASP.NET page.
UserControlA has a string property called StringA that gets generated
from a DB call in it's Page_Load event. I want UserControlB to be
able to access...
| |
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 compile:
T.MyCustomMethod()
The compiler will tell me that it's not sure that the generic type
parameters (<T>) will contain such method and will requires me to constrain
the generic type parameters.
|
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 executable size.
This should not cause any performance issue.
So, is it safe to say that if I can offered to have bigger image size I
can go ahead and use Templates with out worrying about any other
issues?
|
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 property and make its type equal
to ClassB. but i would also like to index this property too. BTW Class B
|
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 = value; }
}
public string someotherstringfield {
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| | |