473,761 Members | 8,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about return type of an overloaded operator

Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:
template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);
Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.

Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:

Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);

assert((vi + vd) == (vd + vi));

The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.

Any thought will be appreciated!

Ben
Jan 19 '06 #1
17 2448
> The above innocent code may not even compile depending on how operator==
is declared. If it did, it is again up to the details of operator== to
decide whether the assertion would succeed or fail. Ideally, both
addition expressions should give Vector<double> because (int() + double
()) is a double.


if you are faced with a dilemma like this, consider how C++'s double
and int may behave in this situation. That helps keep code consistent
and you don't have to parse your mental design each time. Scott Meyer's
book Effective C++ has some insights on overloading. Try it at your
local B&N or Borders.

My 0.000002 cents!

Jan 19 '06 #2
> if you are faced with a dilemma like this, consider how C++'s double
and int may behave in this situation. That helps keep code consistent
and you don't have to parse your mental design each time. Scott Meyer's
book Effective C++ has some insights on overloading. Try it at your
local B&N or Borders.


Thanks for your advices!

As to your first advice, please see that I did make an effort to keep
the semantic consistent with that with C++'s native types. This is
exactly why I want:

// pseudo C++ code
template <typename U, typename V>
Vector<typeof(U ()+V())> operator+ (
const Vector<U>&,
const Vector<V>&);

My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

I will seriously consider your second advice.

Yours,
Ben
Jan 19 '06 #3
benben wrote:
if you are faced with a dilemma like this, consider how C++'s double
and int may behave in this situation. That helps keep code consistent
and you don't have to parse your mental design each time. Scott Meyer's
book Effective C++ has some insights on overloading. Try it at your
local B&N or Borders.


Thanks for your advices!

As to your first advice, please see that I did make an effort to keep
the semantic consistent with that with C++'s native types. This is
exactly why I want:

// pseudo C++ code
template <typename U, typename V>
Vector<typeof(U ()+V())> operator+ (
const Vector<U>&,
const Vector<V>&);

My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.


Ok, I'm a beginner too since the last 4 years or so!

How about you declare an abstract base class B from which U and V
derive, and in operator+ you can have a factory design pattern return
the appropriate type.

Once you have the type returned, you can then overload == to accept
parameters of type base B, which will therefore work in all cases, and
can do comparisons too. I think this should work.

Form wikipedia this is a sample factory pattern:

#include <memory>
using std::auto_ptr;

class Control { };

class PushControl : public Control { };

class Factory {
public:
// Returns Factory subclass based on classKey. Each
// subclass has its own getControl() implementation.
// This will be implemented after the subclasses have
// been declared.
static auto_ptr<Factor y> getFactory(int classKey);
virtual auto_ptr<Contro l> getControl() const = 0;
};

class ControlFactory : public Factory {
public:
virtual auto_ptr<Contro l> getControl() const {
return auto_ptr<Contro l>(new PushControl());
}
};

auto_ptr<Factor y> Factory::getFac tory(int classKey) {
// Insert conditional logic here. Sample:
switch(classKey ) {
default:
return auto_ptr<Factor y>(new ControlFactory( ));
}
}

Jan 19 '06 #4
* benben:

My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.


Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );

template< typename U, typename V >
typename IdToType<sizeof (typeOfArg(U()+ V()).sizer)>::T
operator+( U const& u, V const& v )
{
...
}

I don't know whether it'll work as written.

But I think it better that you use the time to check it all out with a
compiler, than that I should do that... ;-)

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 19 '06 #5
Shark wrote:
How about you declare an abstract base class B from which U and V
derive, and in operator+ you can have a factory design pattern return
the appropriate type.


I forgot to add, that B should be a wrapper around your types. It makes
sense to me, if I understand the problem correctly.

Jan 19 '06 #6
"benben" <be******@yahoo .com.au> wrote in message
news:43******** **************@ news.optusnet.c om.au
Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:
template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);
Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.

Currently I am defaulting U_or_V just to U. But this has some subtle
implications. For example, the breach of the commutative law:

Vector<int> vi(0, 0, 0);
Vector<double> vd(1.1, 1.2, 1.3);

assert((vi + vd) == (vd + vi));

The above innocent code may not even compile depending on how
operator== is declared. If it did, it is again up to the details of
operator== to decide whether the assertion would succeed or fail.
Ideally, both addition expressions should give Vector<double> because
(int() + double ()) is a double.

Any thought will be appreciated!

Ben


The obvious, though somewhat laborious, solution is to specialize the
template for particular (U,V) combinations. Make U the return type in the
general case, and make it V (or perhaps something else --- say complex if U
is real and V is imaginary) for the special cases that need it.

Thus you have the general:

template <class U, class V>
Vector<U> operator+ (const Vector<U>&, const Vector<V>&);

and the specialized:

template <>
Vector<double> operator+ (const Vector<int>&, const Vector<double>& );
Somewhat more elegant would be to define an extra class to indicate the
return type. You can make that class depend on U and V. First we define
the usual case where Vector<U> is satisfactory as the return type.

template<class U, class V>
struct ReturnType
{
typedef Vector<U> type;
};

You can then specialize this for mixed cases that need special handling,
e.g.,

template<>
struct ReturnType<int, double>
{
typedef Vector<double> type;
};
To illustrate its use, consider:
#include <iostream>
using namespace std;

template<class T>
class Vector;

template<class U, class V>
struct ReturnType
{
typedef Vector<U> type;
};

template<>
struct ReturnType<int, double>
{
typedef Vector<double> type;
};
template<class T>
class Vector
{
T array[3];
public:
template<class U, class V>
friend typename ReturnType<U,V> ::type
operator+(const Vector<U>&, const Vector<V>&);
Vector()
{
array[0]=T();
array[1]=T();
array[2]=T();
}
Vector(T first, T second, T third)
{
array[0] = first;
array[1] = second;
array[2] = third;
}
T operator[](int index) const
{
return array[index];
}
T &operator[](int index)
{
return array[index];
}
};

template <class U, class V>
typename ReturnType<U,V> ::type
operator+(const Vector<U>&lhs, const Vector<V>&rhs)
{
typename ReturnType<U,V> ::type sum;
sum[0] = lhs[0]+rhs[0];
sum[1] = lhs[1]+rhs[1];
sum[2] = lhs[2]+rhs[2];
return sum;
}

int main()
{
Vector<int> i(4,2,5);
Vector<double> d(1.2, 2.4, 7.2);

Vector<double> result = i+d;

cout << result[0] << ',' << result[1] << ',' << result[2] << '\n';
return 0;
}
--
John Carson


Jan 19 '06 #7
benben wrote:
Given a class template Vector<>, I would like to overload operator +.
But I have a hard time deciding whether the return type should be
Vector<U> or Vector<V>, as in:
template <typename U, typename V>
Vector<U_or_V> operator+ (
const Vector<U>&,
const Vector<V>&);
Naturally, I would like U_or_V to be the type of (U() + V()), but,
pardon my limited knowledge, I have no idea how to achieve that.


Seriously take a look at Boost.Typeof typeof emulation in the latest
version of the boost libraries. It is very comprehensive and great for
just this situation.

Useage would be something like:

template <typename U, typename V>
Vector< BOOST_TYPEOF_TP L(U() + V())> operator+ (
const Vector<U>&,
const Vector<V>&);

You may have to do some work to 'register' U and V though Boost.Typeof
can make use of compiler extensions in some cases too. 'registration'
is covered in the documentation. There are some differences between use
with templates and non_templates too, but its probably the nearest to
true language support.

Check it out.

regards
Andy Little

Jan 19 '06 #8
Alf P. Steinbach wrote:
* benben:
My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );


Thanks for your reply alf! But I am very confused with the code,
especially the line immediately above.

template< typename U, typename V >
typename IdToType<sizeof (typeOfArg(U()+ V()).sizer)>::T
operator+( U const& u, V const& v )
{
...
}

I don't know whether it'll work as written.
It will take some time before I can fully digest the code above. I am
under the impression this method relies on type size to work out the
resultant type. Please pardon my impoliteness but I don't see the above
could select, for example, double from a int-double pair.

But I think it better that you use the time to check it all out with a
compiler, than that I should do that... ;-)


Thank you! I will.

Ben
Jan 19 '06 #9
* benben:
Alf P. Steinbach wrote:
* benben:
My problem is how to write typeof(U()+V()) in a way that the compiler
would understand. I have considered a traits class but specializations
will be endless in that case.

Consider something like

template< unsigned Id > struct IdToType;
template<> struct IdToType<1> { typedef char T; };
template<> struct IdToType<2> { typedef unsigned char T; };
...

template< typename T > struct TypeToId;
template<> struct TypeToId<char> { enum{ id = 1 }; };
...

template< unsigned Id > struct MyTypeId { char sizer[Id]; };

template< typename T > MyTypeId< TypeToId<T>::id > typeOfArg( T );


Thanks for your reply alf! But I am very confused with the code,
especially the line immediately above.


It's meant to be a function, not implemented anywhere, returning a
struct where the size of that struct's 'sizer' identifies the argument
type. This struct is then passed to sizeof (so that the function is
never actually called), the result of sizeof used to obtain the type
from TypeToId mapping. The point being that you only have to define
O(n) type mapping classes for n supported types, instead of O(n^2).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 19 '06 #10

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

Similar topics

35
4548
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I go to great lengths to restructure my code just to look concise and make it more manageable. When I say this, I'm also referring to the way I write my functions. It seems to me sometimes that I shouldn't have many void functions accepting...
8
17877
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said the following :
4
4288
by: wongjoekmeu | last post by:
Hello All, I know that when you pass an argument to a function (if you want let the function be able to change the value) then you can choose to pass the argument by reference or a pointer to that argument. Now my question is, why would you prefer to let a function return a reference or a pointer ??? Consider the following with operator overloading. I suppose the operator can be seen as a function (right ?)
7
1831
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class xydata with operator- overloaded: class xydata { public:
2
2744
by: Wiktor Zychla | last post by:
I've read several documents about upcoming C# generics and I still cannot understand one thing. Would it be valid to write a code like this: class SomeClass { public void AMethod<T>(T a, T b) { T c = a + b; // ?
10
2621
by: Grizlyk | last post by:
1. Can abybody explain me why C++ function can not be overloaded by its return type? Return type can has priority higher than casting rules. For example: char input(); //can be compiled to name "input$char$void" int input(); //can be compiled to name "input$int$void" .... int i= 3+'0'+input(); //can be compiled to: int(3)+int('0')+input$int$void()
3
1749
by: iluvatar | last post by:
Hi all. I have written a 3d-vector class (for 3-dimensional space) and I have overloaded the arihtmetic operators like +, +=, * and so on. Also, the constructor works with doubles and has default arguments. In my class, the operator = works for another vector (just copying the elements), and for a double: in this cases each element of the vector will be equal to the double. Example:
8
1217
by: Tony Johansson | last post by:
Hello! I think that this text is complete enough so you can give me an explanation what they mean with it. I wonder if somebody understand what this means. It says the following : "You can't overload assignment operator, such as +=, but these operator use their simple counterpart, such as +, so you don't have to worry about that. Overloading + means that += will function as expected. The = operator is included in this -- it makes little...
1
1506
by: Nikhil.S.Ketkar | last post by:
Hi, Does the following construct qualify as overloading on return type ? If not, in what way ? I overloaded the type conversion operator and used pointers to member functions. Its pretty straightforward but I am sure I have missed as this is not supposed to be possible. Am I misunderstanding overloading ?
0
9376
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
9988
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...
1
9923
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
8813
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
7358
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
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
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.