473,767 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Typecasting operator on simple types vs. classes

Hi! I'm having a little trouble with the typecast operator, can anybody
help me with the rules for when the this operator is invoked?

In the class 'Test' in the code below, the typecast operator returns a
'mytype'. In main() I use the [] operator on 'Test'-class objects. If
'mytype' is a pointer the [] operator works fine. But if I instead try
to call an overloaded [] operator, the typecast operator is not invoked,
and I get a compiler error (unless I make an explicit cast.) So does the
'operator mytype ()' only work properly with simple types?

Any help would be appreciated!

Nico

template <class mytype>
class Test
{
mytype i;

public:

operator mytype () {return i;}
};

class Test2
{
public:
int operator [] (int i) {return i;}
};

int main(void)
{
Test<double*> t1;
Test<Test2> t2;

t1[0]; // This line works fine
t2[0]; // This line doesn't compile
((Test2)t2)[0]; // This also works

return 0;
}

Jul 19 '05 #1
7 4544
Nicolay Korslund wrote:

<SNIP>
In the class 'Test' in the code below, the typecast operator returns a
'mytype'. In main() I use the [] operator on 'Test'-class objects. If
'mytype' is a pointer the [] operator works fine. But if I instead try
to call an overloaded [] operator, the typecast operator is not invoked,
and I get a compiler error (unless I make an explicit cast.) So does the
'operator mytype ()' only work properly with simple types? <SNIP>
template <class mytype>
class Test
{
mytype i;

public:

operator mytype () {return i;}
};

class Test2
{
public:
int operator [] (int i) {return i;}
};

int main(void)
{
Test<double*> t1;
Test<Test2> t2;

t1[0]; // This line works fine
t2[0]; // This line doesn't compile
((Test2)t2)[0]; // This also works

return 0;
}


There is a rule that in a conversion sequence only one use-defined
conversion operator is allowed.
My guess is that the rule covers overloaded operators too.
t1[0] works because there is only one use-defined conversion is involved :
operator mytype () {return i;}
It returns object of double* type for which built-in [] operator is defined.
t2[0], however, casts through the above user-defined conversion to Test2
type, which, in turn, has only use-defined [] operator. Of course, when you
remove one of user-defined operators from implicit sequence by explicit
typecasting, everything works: ((Test2)t2)[0]

I would suggest adding [] operator to the *Test* class, like this

int operator[](int ind) {return i[ind];}

Then you don't have to think about typecasting.

Nikolai Borissov
Jul 19 '05 #2
Nikolai Borissov wrote:
Nicolay Korslund wrote: I would suggest adding [] operator to the *Test* class, like this

int operator[](int ind) {return i[ind];}

Then you don't have to think about typecasting.


Except that t1[0] returns a double and t2[0] returns an int.

I'm thinking the other answer is a proxy class.

Jul 19 '05 #3
Nicolay Korslund wrote:
Hi! I'm having a little trouble with the typecast operator, can anybody
help me with the rules for when the this operator is invoked?

In the class 'Test' in the code below, the typecast operator returns a
'mytype'. In main() I use the [] operator on 'Test'-class objects. If
'mytype' is a pointer the [] operator works fine. But if I instead try
to call an overloaded [] operator, the typecast operator is not invoked,
and I get a compiler error (unless I make an explicit cast.) So does the
'operator mytype ()' only work properly with simple types?

Any help would be appreciated!

Nico

template <class mytype>
class Test
{
mytype i;

public:

operator mytype () {return i;}
};

class Test2
{
public:
int operator [] (int i) {return i;}
};

int main(void)
{
Test<double*> t1;
Test<Test2> t2;

t1[0]; // This line works fine
t2[0]; // This line doesn't compile
((Test2)t2)[0]; // This also works

return 0;
}


I'm not sure why the code above does not work. There seems to be only
one conversion operator and one operator[] definition. I looked through
the copy of the standard I have and it is unfortunatly very wordy about
the subject and hard to filter the relevant pieces.
This is another version of your example that does work. (at least on gcc
3.3.1).
template <class mytype> class TestProxy;

template <class mytype>
class Test
{
friend class TestProxy<mytyp e>;
mytype v;

public:

operator mytype & ()
{
return v;
}

TestProxy<mytyp e> operator [] (int i);

};

template <typename T>
class PtrType
{
public:
typedef int Type; // HACK ALERT
};

template <typename T>
class PtrType<T*>
{
public:
typedef T & Type;
};

template <class mytype> class TestProxy
{
public:

Test<mytype> & m_test;
int m_i;

TestProxy( Test<mytype> & i_test, int i )
: m_test( i_test ),
m_i( i )
{
}

operator typename PtrType<mytype> ::Type ()
{
return m_test.v[m_i];
}
};

template <class mytype>
inline TestProxy<mytyp e> Test<mytype>::o perator [] (int i)
{
return TestProxy<mytyp e>( *this, i );
}

class Test2
{
public:
int operator [] (int i)
{
return i;
}

};

int main(void)
{
Test<double*> t1;
Test<Test2> t2;

t1[1]; // This line works fine
int x = t2[2]; // This line doesn't compile
((Test2)t2)[3]; // This also works

return 0;
}

Jul 19 '05 #4
Gianni Mariani wrote:
Nikolai Borissov wrote:
Nicolay Korslund wrote:
I would suggest adding [] operator to the *Test* class, like this

int operator[](int ind) {return i[ind];}

Then you don't have to think about typecasting.


Except that t1[0] returns a double and t2[0] returns an int.


That's right, because t1 and t2 are objects of different type. It's already
not a technical matter, rather a design one.
OP is supposed to know the purpose of his design. Maybe t1[] being of type
int and t2[] of type double is exactly what he wants.
I'm thinking the other answer is a proxy class.


And I'm thinking about Occum's Razor:

"Entities must not be multiplied beyond what is necessary"

Here's an original Latin version:

"Pluralitas non est ponenda sine neccesitate"

Nikolai Borissov
Jul 19 '05 #5
Nikolai Borissov wrote:
Gianni Mariani wrote:
Nikolai Borissov wrote:
Nicolay Korslund wrote:
I would suggest adding [] operator to the *Test* class, like this

int operator[](int ind) {return i[ind];}

Then you don't have to think about typecasting.


Except that t1[0] returns a double and t2[0] returns an int.

That's right, because t1 and t2 are objects of different type. It's already
not a technical matter, rather a design one.
OP is supposed to know the purpose of his design. Maybe t1[] being of type
int and t2[] of type double is exactly what he wants.
I'm thinking the other answer is a proxy class.

And I'm thinking about Occum's Razor:

"Entities must not be multiplied beyond what is necessary"


The counter is the Mariani conjecture.

"unneccessa rily complex solutions are a product of adopting
unneccessarily simple tools".

Here is the orginal in English.

If you use tools too simple for the given task you will end up with a
solution that is more complex than neccassary.

Here's an original Latin version:

"Pluralitas non est ponenda sine neccesitate"


Jul 19 '05 #6

Gianni Mariani wrote:
The counter is the Mariani conjecture.

"unneccessa rily complex solutions are a product of adopting
unneccessarily simple tools".

Here is the orginal in English.

If you use tools too simple for the given task you will end up with a
solution that is more complex than neccassary.


Good addendum to Occum's Razor :))

I've realized what's the problem with returning correct type.
Should be interesting to think about it the other day (just don't have time
now).
I'll analyze your solution too.

Ciao

Nikolai Borissov
Jul 19 '05 #7
> I've realized what's the problem with returning correct type.
Should be interesting to think about it the other day (just don't have time
now).
I'll analyze your solution too.


Ok, thank you both for the help.

Nicolay

Jul 19 '05 #8

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

Similar topics

5
3036
by: Vijai Kalyan | last post by:
Hello, I have come back to C++ after a couple of years with Java so I am quite rusty and this question may seem poor: My platform is Windows XP with MSVC 7.1. I have a class with a templatized conversion operator defined as follows:
20
3871
by: Patrick Guio | last post by:
Dear all, I have some problem with insertion operator together with namespace. I have a header file foo.h containing declaration of classes, typedefs and insertion operators for the typedefs in a named namespace namespace foo { class Foo
11
4424
by: Vinod Patel | last post by:
I have a piece of code : - void *data; ...... /* data initialized */ ...... struct known_struct *var = (struct known_struct*) data; /*typecasting*/ How is this different from simple assignment. int b = some_value;
5
2048
by: Peter Seaman | last post by:
I do recognise a number of very appealing features of C#, in particular the strong typing and the need in some contexts to be very explicit regarding your intention. But the most common operator - assignment -seems to me a right source of confusion and mistakes because it has two very different meanings. Why not have one syntax for value assigment and a different syntax for aliasing? With classes you might be permitted both types of...
7
2187
by: Raghu | last post by:
Hello All, I need some help regarding overloading operation. Is there any way to overload typecasting? I mean if i have a piece of code as below. int a = 2: float b; b = (float)a;
6
3549
by: Bill foust | last post by:
I'm running into a situation there I think an operator overload would solve the issue, but I'm unable to make it work for some reason. If anyone can help here I would appreciate it. I have a base class that is common to many other classes. public class Base .... end class I have 2 seperate classes that inherit from base
6
3210
by: Nishu | last post by:
Hi all, What is difference between typecasting and casting? I used to think that both are same; but few days back someone pointed out here that these are different. Vague guess, Is it that typecasting means casting using typedef? I just want to confirm it. Thanks, Nishu
14
2343
by: Hunk | last post by:
Hi I ws wondering if there is a way to implement operator+ in case of virtual classes. Here's the problem. I have to have a base string class from which two classes (normal char string and a hash string class ) are derived. The two derived classes are template classes specifying the sizes. The base class is a non-template class so that it can be used generically in the interface classes. the design would look like
19
3528
by: C++Liliput | last post by:
I have a custom String class that contains an embedded char* member. The copy constructor, assignment operator etc. are all correctly defined. I need to create a map of my string (say a class called MyString) and an integer i.e. std::map<MyString, int>. Whenever I insert the elements in the map using the subscript operator, I noticed that the copy constructor for MyString is invoked more number of times than if I do it using the insert()...
0
10169
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...
1
9960
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,...
0
9841
tracyyun
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...
1
7383
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
6655
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
5280
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
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2807
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.