473,666 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading 'casting' operator

Hi all,

I have a templated Vector3D class which holds (x,y,z) components as the
specified type. I quite often wish to cast a Vector3D holding ints into
a Vector3D holding floats and vice versa. Like so:

Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = intVec;

Of course this doesn't work. I would be happy if instead the following
worked:
Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = static_cast< Vector3D<float> >(intVec);

but of course that doesn't either. I have read online that it is not
possible to overload the static_cast operator (why, incidently?) but
what is the best approach to this problem? Ideally I would like the
first example to compile but generate a warning and the second example
to be fine (as works for built-in types).

Any thoughts appriciated,

David
Jan 17 '06 #1
8 9172
For the first one, I think you can overload = by
template <class T>
class Vector3D{
.....
template <class N> operator=(const Vector3D<N>& rvalue)
{....}
.....
};
my first reply may not be correct.

I don't know the answer to the second one though.
David Williams wrote:
Hi all,

I have a templated Vector3D class which holds (x,y,z) components as the
specified type. I quite often wish to cast a Vector3D holding ints into
a Vector3D holding floats and vice versa. Like so:

Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = intVec;

Of course this doesn't work. I would be happy if instead the following
worked:
Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = static_cast< Vector3D<float> >(intVec);

but of course that doesn't either. I have read online that it is not
possible to overload the static_cast operator (why, incidently?) but
what is the best approach to this problem? Ideally I would like the
first example to compile but generate a warning and the second example
to be fine (as works for built-in types).

Any thoughts appriciated,

David


Jan 17 '06 #2
David Williams wrote:
I have a templated Vector3D class which holds (x,y,z) components as the
specified type. I quite often wish to cast a Vector3D holding ints into
a Vector3D holding floats and vice versa. Like so:

Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = intVec;

Of course this doesn't work. I would be happy if instead the following
worked:
Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = static_cast< Vector3D<float> >(intVec);

but of course that doesn't either. I have read online that it is not
possible to overload the static_cast operator (why, incidently?) but
what is the best approach to this problem? Ideally I would like the
first example to compile but generate a warning and the second example
to be fine (as works for built-in types).


Without code showing the definition of template<typena me T> Vector3D,
it's difficult to respond. See the FAQ:

http://www.parashift.com/c++-faq-lit...t.html#faq-5.8

As another poster said, a templated operator=() may give you what you
want for the first issue. For the second issue, although you can't
overload the static_cast operator directly, you could make the
static_cast operator work the way you want by providing a templated
copy constructor - something like (VERY untested code):

template<typena me T> class Vector3D {
public:
template<typena me U>
explicit Vector3D(const Vector3D<U>&);
};

Best regards,

Tom

Jan 17 '06 #3
David Williams wrote:
I have a templated Vector3D class which holds (x,y,z) components as the
specified type. I quite often wish to cast a Vector3D holding ints into
a Vector3D holding floats and vice versa. Like so:

Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = intVec;
What you need here is not, as other have suggested, an overloaded
operator=. This is not assignment, but initialization -- i.e.,
construction. For construction, we use constructors. If you define a
single-argument constructor which takes another Vector3D of a different
type, you can do what you want here. It's important to recognize the
difference, though, between the above, assignment, and casting.

Initialization (construction) creates a new instance, based in some way
on the parameter(s) provided to the constructor.

Assignment modifies an existing instance, based in some way on the
parameter provided to operator=.

Casting is more complicated -- it depends on whether you're casting by
value, pointer, or reference. What's more, it is possible to provide
an overloaded "conversion operator" (not casting operator) which allows
implicit (or explicit, if that keyword is used) conversion to another
type. A conversion operator is sort of the inverse of a constructor.
Of course this doesn't work. I would be happy if instead the following
worked:

Vector3D<int> intVec(10,20,30 );
Vector3D<float> floatVec = static_cast< Vector3D<float> >(intVec);


You should not be satisfied with this. Implement an appropriate
single-argument constructor and you'll have a better result.

Luke

Jan 17 '06 #4
Luke Meyers wrote:
David Williams wrote:
I have a templated Vector3D class which holds (x,y,z) components as the
specified type. I quite often wish to cast a Vector3D holding ints into
a Vector3D holding floats and vice versa. Like so:

Vector3D<in t> intVec(10,20,30 );
Vector3D<floa t> floatVec = intVec;

What you need here is not, as other have suggested, an overloaded
operator=. This is not assignment, but initialization -- i.e.,
construction. For construction, we use constructors. If you define a
single-argument constructor which takes another Vector3D of a different
type, you can do what you want here. It's important to recognize the
difference, though, between the above, assignment, and casting.


Ah yes, I can see that now. However, could it be argued (according to
the 'Big Three' rule) that if I have a custom constructor I should have
a custom assignment operator as well?

Initialization (construction) creates a new instance, based in some way
on the parameter(s) provided to the constructor.
Great, this now seems to work:

template <typename Type>
template <typename CastType>
Vector3D<Type>: :Vector3D(const Vector3D<CastTy pe>& vectorToSet)
{
m_tX = vectorToSet.x() ;
m_tY = vectorToSet.y() ;
m_tZ = vectorToSet.z() ;
}

Assignment modifies an existing instance, based in some way on the
parameter provided to operator=.

Casting is more complicated -- it depends on whether you're casting by
value, pointer, or reference. What's more, it is possible to provide
an overloaded "conversion operator" (not casting operator) which allows
implicit (or explicit, if that keyword is used) conversion to another
type. A conversion operator is sort of the inverse of a constructor.
I found the following code and modified it for my class. Is this the
'conversion operator' you are refering to?

template <typename Type>
template <typename CastType>
Vector3D<Type>: :operator Vector3D<CastTy pe> () throw()
{
return Vector3D<CastTy pe>(m_tX,m_tY,m _tZ);
}

I was confused by the fact that the return type (Vector3D<CastT ype>)
appears to come between 'operator' and the empty brackets. But it's ok?

Of course this doesn't work. I would be happy if instead the following
worked:

Vector3D<in t> intVec(10,20,30 );
Vector3D<floa t> floatVec = static_cast< Vector3D<float> >(intVec);

Come to think of it, I could write a vector_cast function to do the
same. However, given what I now know I don't think it's necessary.

You should not be satisfied with this. Implement an appropriate
single-argument constructor and you'll have a better result.

Luke


Thanks for your help!
Jan 17 '06 #5
David Williams wrote:
Ah yes, I can see that now. However, could it be argued (according to
the 'Big Three' rule) that if I have a custom constructor I should have
a custom assignment operator as well?


No. The 'Big Three' in the rule are specifically the copy constructor,
assignment operator and destructor. The functions that the compiler
will generate for you if your don't define them yourself. If you need
to write your own version of any one of these three, you probably need
to write them all yourself because the compiler generated ones probably
will not do what you want. There is nothing in the 'rule' about any
other constructors you may write.

Gavin Deane

Jan 17 '06 #6
Luke Meyers wrote:
What you need here is not, as other have suggested, an overloaded
operator=. This is not assignment, but initialization -- i.e.,
construction. For construction, we use constructors. If you define a
single-argument constructor which takes another Vector3D of a different
type, you can do what you want here. It's important to recognize the
difference, though, between the above, assignment, and casting.


I agree... but didn't I suggest exactly that?

Best regards,

Tom

Jan 17 '06 #7
Gavin Deane wrote:
David Williams wrote:
Ah yes, I can see that now. However, could it be argued (according to
the 'Big Three' rule) that if I have a custom constructor I should have
a custom assignment operator as well?

No. The 'Big Three' in the rule are specifically the copy constructor,
assignment operator and destructor. The functions that the compiler
will generate for you if your don't define them yourself. If you need
to write your own version of any one of these three, you probably need
to write them all yourself because the compiler generated ones probably
will not do what you want. There is nothing in the 'rule' about any
other constructors you may write.

Gavin Deane


Ok, thanks.
Jan 17 '06 #8
Yeah, you're right. It's copy constructor instead of assignment
operator, thanks for pointing out.

Jan 18 '06 #9

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

Similar topics

3
2590
by: David.H | last post by:
Good evening everyone, Im using this code to get an idea on overloading the + operator: class Graph { public: Graph(void); Graph(int valX, int valY); Graph operator+(const Graph&); int getx(void) { return x; }
2
3826
by: ryan.fairchild | last post by:
I have a problem I am trying to create a MyInt class to hanlde very large ints. Its for a class, therefore I can only do what the teach tells me. I want to be able to overload the insertion operator so that I can read in one digit at a time from the buffer and if the digit is 0 - 9 then put it into the dynamic array which stores each digit of this large int. #include <iostream> #include <string> #include "myint.h"
4
2474
by: hall | last post by:
Hi all. I have run into a problem of overloading a templatized operator>> by a specialized version of it. In short (complete code below), I have written a stream class, STR, which defines a templatized operator>>() as a member that can deal with the built in C types (int, char, float...) template <class tType> STR& STR::operator>>(tType & t); I then attempted to add an overloaded version of this to support my own
2
1300
by: Peter | last post by:
Hello, Thanks for reviewing my question. I am trying to override the = operator for my UserControl class; However, I am getting a syntax error. public class MyClass { private int x = 0; public static UserControl1 operator =(int y)
3
1644
by: Suresh Tri | last post by:
Hi all, I was trying to overload '<' operator for (varchar,varchar). But in the function which handles the comparision I want to use the previous '<' operator.. but it is going into a recursion. My simplified code looks like : create or replace function orastringcmp (varchar, varchar) returns boolean as 'declare
12
8065
by: Achim Domma | last post by:
Hi, I want to use Python to script some formulas in my application. The user should be able to write something like A = B * C where A,B,C are instances of some wrapper classes. Overloading * is no problem but I cannot overload the assignment of A. I understand that this is due to the nature of Python, but is there a trick to work around
16
4338
by: EM.Bateman | last post by:
Working on Visual Studio .Net I've implemented a class: #ifndef CONTRIBUTOR_H #define CONTRIBUTOR_H enum Gender {male=1, female, unk}; #include <iostream> #include <iomanip> #include <string>
4
1468
by: UofFprogrammer | last post by:
Hello, I was taking a look at overloading the = operator in a C Plus Plus book. Part of the code of the overloaded =operator included checking for the case when the same object was on both sides of the equal sign. When and why would you have a situation like this? someobject1=someobject1; Thank You
9
15259
by: Faisal | last post by:
Hi, Why C++ doesn't allow overloading of size of operator. I think it would be much handy to check the type userdefined types. For eg. In my project, I've some structures which contains dynamic data( pointers). So if i have some way to overload the sizeof operator I can calculate the exact size and return.
0
8440
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
8866
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
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8638
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...
0
7381
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
6191
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
5662
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();...
1
2769
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1769
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.