473,748 Members | 8,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Property template

Hello,

This is my first attempt at template programming so please bear with me.
This is what I have so far:

Property.h --------------------------

#ifndef PROPERTY_H_
#define PROPERTY_H_

enum Access{ READ, WRITE, FULL };

template<typena me T, Access type = FULL>
class Property
{
public:
Property(const T& val, T (*getter)(T) = defaultGet, T (*setter)(T,
T) = defaultSet ): value(val) { Get = getter; Set = setter; }
virtual operator T() { return Get(value); }
virtual T operator=( T& val ) { return Set(value, val); }
protected:
T value;
T (*Get) (T);
T (*Set) (T, T);
static T defaultGet(T val) { return val; }
static T defaultSet(T dest, T source) { dest = source; }
};

#endif
and here is my test program:

main.cpp ---------------------------------

#include <cstdlib>
#include <iostream>

#include "Property.h "

static int anotherGetter(i nt value) { return 10; }

int main(int argc, char *argv[])
{
Property<int> t(1);
std::cout << t << std::endl;
t = 5;
std::cout << t << std::endl;
t = 2;
std::cout << t << std::endl;
// Up to here everything works fine but:
Property<int> f(1, anotherGetter);
std::cout << f << std::endl; // This returns 10 like it's supposed to
f = 5;
std::cout << f << std::endl;
// But this returns 5 not 10
f = 2;
std::cout << f << std::endl;
// And again this returns 2 not 10.
system("pause") ;
}

My question is why does it work the way I intended the first time but not
the second or third time?

Any help would be appreciated
Nov 23 '05 #1
5 2552
t=5,t=2,f=5,f=2 calls your copy constructor (your constructor is used
as a copy constructor)

Nov 23 '05 #2
On Tue, 22 Nov 2005 06:58:15 -0500, "Brent Ritchie"
<br**********@p ersonainternet. com> wrote:
Hello,

This is my first attempt at template programming so please bear with me.
This is what I have so far:

Property.h --------------------------

#ifndef PROPERTY_H_
#define PROPERTY_H_

enum Access{ READ, WRITE, FULL };

template<typen ame T, Access type = FULL>
class Property
{
public:
Property(const T& val, T (*getter)(T) = defaultGet, T (*setter)(T,
T) = defaultSet ): value(val) { Get = getter; Set = setter; }
virtual operator T() { return Get(value); }
virtual T operator=( T& val ) { return Set(value, val); }
protected:
T value;
T (*Get) (T);
T (*Set) (T, T);
static T defaultGet(T val) { return val; }
static T defaultSet(T dest, T source) { dest = source; }
};

#endif
and here is my test program:

main.cpp ---------------------------------

#include <cstdlib>
#include <iostream>

#include "Property.h "

static int anotherGetter(i nt value) { return 10; }

int main(int argc, char *argv[])
{
Property<int> t(1);
std::cout << t << std::endl;
t = 5;
std::cout << t << std::endl;
t = 2;
std::cout << t << std::endl;
// Up to here everything works fine but:
Property<int> f(1, anotherGetter);
std::cout << f << std::endl; // This returns 10 like it's supposed to
f = 5;
std::cout << f << std::endl;
// But this returns 5 not 10
f = 2;
std::cout << f << std::endl;
// And again this returns 2 not 10.
system("pause") ;
}

My question is why does it work the way I intended the first time but not
the second or third time?

Any help would be appreciated


Your assignment

f = 5;

is inadvertently (to you) interpreted as

f = Property<int>(5 );

instead of

f.operator=(5);

In other words, a temporary Property<int> object is created, which is then
assigned to f.

The reason for this behavior is that your assignment operator takes a
non-const T&. Make sure that your assignment operators are in the form:

T& operator=(const T&);

A constructor that can be called with a single argument is also likely to
cause this kind of automatic temporary object creation. Perhaps you should
declare your constructor explicit.
Nov 23 '05 #3
Brent Ritchie wrote:
Property<int> f(1, anotherGetter);
std::cout << f << std::endl; // This returns 10 like it's supposed to
f = 5;
std::cout << f << std::endl;
// But this returns 5 not 10


I guess the problem is this:
The expression 'f = 5' creates a new Property object using the copy
constructor and assigns it to 'f'. Since you are setting the default
getter in the copy constructor, it returns 'value' and not '10', so the
output is '5'.

Try making your copy constructor explicit, then it must not be used for
type conversion. Another issue might be that AFAICT you operator= has a
wrong signature: 'val' should be of type reference-to-const T, not
reference-to-T.

Hope that helps,
Matthias
Nov 23 '05 #4
Matthias Kaeppler wrote:
Try making your copy constructor explicit, then it must not be used for
type conversion.


One more note about copy constructors:

Although your copy constructor has /three/ formal parameters, it can be
called by the client only taking /one/ argument, since you're assigning
default values to parameters two and three.
Since every copy constructor which can be called using one argument
qualifies for implicit type conversion, you should make it 'explicit',
unless you want type conversion to happen (this form of conversion can
be very useful, but it's also error prone because it's hard to
detect--as you probably noted yourself now).

One more C++ subtlety which pops up now and then :)

Regards,
Matthias
Nov 23 '05 #5
Thanks all,

This is what I have so far for my C++ Property Template:

Property.h-------------------------

#ifndef PROPERTY_H_
#define PROPERTY_H_

enum Access{ READ, WRITE, FULL };

template<typena me T, Access type = FULL>
class Property
{
public:
explicit Property( const T& val,
const T (*getter)(const T&) = defaultGet,
const T (*setter)(T&, const T&) = defaultSet )
: value(val)
{
if (getter == NULL)
{
Get = defaultGet;
}
else { Get = getter; }
if ( setter == NULL )
{
Set = defaultSet;
}
else
{
Set = setter;
}
}

explicit Property( Property *val )
{
val.value = this->value;
val.Get = this->Get;
val.Set = this->Set;
}

virtual operator T()
{
return Get(value);
}
virtual T operator=( const T& val )
{
return Set(value, val);
}

protected:
const T (*Get) ( const T& );
const T (*Set) ( T&, const T& );
T value;

static const T defaultGet(cons t T& val)
{
return val;
}

static const T defaultSet(T& dest, const T& source)
{
dest = source;
return dest;
}

};

#endif

main.cpp-----------------------------

#include <cstdlib>
#include <iostream>

#include "../Property.h"

static const int anotherGetter(c onst int& value) { return value * -1; }
static const int anotherSetter(i nt& value, const int& value2 ) { value +=
value2; return value; }

int main(int argc, char *argv[])
{
int i = 0;

Property<int> a(2);
std::cout << "Property<i nt> a(2)" << std::endl;
std::cout << "Input value to test default set functionality: ";
std::cin >> i;
a = i;
std::cout << "Testing default get functionality: ";
std::cout << a << std::endl << std::endl;

Property<int> b(2, anotherGetter);
std::cout << "Property<i nt> b(2, anotherGetter)" << std::endl;
std::cout << "Input value to test default set functionality: ";
std::cin >> i;
b = i;
std::cout << "Testing anotherGetter functionality: ";
std::cout << b << std::endl << std::endl;

Property<int> c(2, NULL, anotherSetter);
std::cout << "Property<i nt> c(2, NULL, anotherSetter)" << std::endl;
std::cout << "Input value to test anotherSetter functionality: ";
std::cin >> i;
c = i;
std::cout << "Testing default get functionality: ";
std::cout << c << std::endl << std::endl;

Property<int> d(2, anotherGetter, anotherSetter);
std::cout << "Property<i nt> d(2, anotherGetter, anotherSetter)" <<
std::endl;
std::cout << "Input value to test anotherSetter functionality: ";
std::cin >> i;
d = i;
std::cout << "Testing anotherGetter functionality: ";
std::cout << d << std::endl << std::endl;

Property<int> x = d;
std::cout << x << std::endl;
x = 2;
std::cout << x << std::endl;
x = 1;
std::cout << x << std::endl;
system("pause") ;

return 0;

}

Next, I'm going to add the overloaded versions of this template for
read-only and write-only access. Then I'm going to start testing all
primitives not just int. Then I have to start testing user defined classes.
<shutters>

Any comments on what I have so far? Anything you see as potentially
broken? Feature changes/requests ;) ? Anyone think this might be potentially
useful to anyone but me?

Also if you notice this compiles nicely with no warnings even with -Wall
turned on. I think thats a first for me!

Anyways, Thanks for all the help. This template programming isn't all
that different from regular programming but it has it's nuances though.
Nov 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

43
5012
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own libraries. I'm not sure if that's a good thing or not. AFAIK, most of Qt is compatable with the Standard Library. That is, QLT can interoperate with STL, and you can convert back and forth between std::string and Qt::QString, etc. Are there any...
9
3674
by: Rakesh | last post by:
Hi, I am able to obtain a MenuItem object's Name property @ design-time, but am not able to get the same @ run- time...why? And since MenuItem doesn't inherit from Control class, it's not even supposed to be available @ design-time right?
1
3973
by: The_Rave | last post by:
Hi everyone, I'm trying to add my own template columns to the property builder of ..NET. E.g. a checkbox column, or an image column. But I can't find the sources of the wizard, or a way to add them to the wizard, via add-in? I tried to capture it with a macro, but all I can't get out of it is the raise event of the wizard, nothing that happens during the wizard. "
3
4436
by: Ricardo Maciel | last post by:
The How to page: http://msdn2.microsoft.com/en-us/library/7aw8zc76(VS.80).aspx walks through the creation of MDI child forms. It includes instructions to set the property MdiList to maintain a list of open MDI child windows. However, I can't find the MdiList property in the properties panel.
0
1986
by: Memfis | last post by:
While I was looking through the group's archives I came across a discussion on doing properties (as known from Delphi/C#/etc) in C++. It inspired me to do some experimenting. Here's what I came up with. First we have an interface defining how a property can be used (read and written - for simplicity, I ignored read-only and write-only variants). template<typename Tclass Property { public:
2
9104
by: kashif | last post by:
Hello All, I am trying to crete alerts using SharePoint V3 API and so far I am able to create alerts but for some reason I could not figure out how to set AlertTemplate property on SPAlert object. Here is my code. sPAlert = sPUser.Alerts.Add(); sPAlert.AlertType = SPAlertType.List; sPAlert.AlertTemplate = sPAlertTemplate;
1
2035
by: berny.zamora | last post by:
Hello everyone, I have a composite control (lets call it the parent) that contains a datalist. The datalist has an ItemTemplate that contains another composite control (lets call it the child). I am trying to create a property at the parent control that sets a property in the child instances. So for example lets say I am creating a control that displays a list of hotel reservations for a group of people.
2
1527
by: C. Herzog | last post by:
Hi! I want to create a huge amount of classes. All classes have in common that the change of a property should fire an Change-Event and maybe do other things. I don't want to write thousand times the same things like that: Public Property Price() As Double Get
0
886
by: christian2.schmidt | last post by:
Hi, I tried to implement the std::swap method on properties (and indexers) without success. The problem is that list calls the getter and returns a copy and the assignment in the swap method does not call the setter. template <typename T> void swap(T% a, T% b) { T t = a; a = b; b = a; }
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
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,...
0
9541
Oralloy
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...
0
8242
agi2029
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...
1
6796
isladogs
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...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
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...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2215
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.