473,770 Members | 6,736 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
17 2451
Shark wrote:
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.


Thank you shark!

The challenge is, I can't insert a base class for U and V because they
can be anything from built-in types (int, double, char, etc) to types
that must not exhibit virtuality (hence must not have an abstract base.)

It is possible though, as you have reminded me, to design a secondary
type to hold the operands temporarily and only evaluate the result
against a certain type upon assignment.

But this will render the orginal design far more complex and much less
maintainable.

Anyway your help was much appreciated!

Ben
Jan 19 '06 #11
this is good idea.....but there are a problem, RTTI(as "typeof") is a
technique for run-time. but the template argument be sure in
complier-time...

Jan 19 '06 #12
Thank you John for the time and effort in your reply! I much appreciated.

I did considered using a traits class. I can put my effort in and give
all the specializations necessary for built-in types. But as the vector
class also takes class types it is required of the USER of the vector
class to provide specializations of whatever custom type they use.
Whether the user remembers (or cares) to give a specialization would
have an implication on the semantic, which can be subtle. And this holds
me back from using a traits class to determine the return type.

Yours,
Ben

Jan 19 '06 #13

an**@servocomm. freeserve.co.uk wrote:
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


Much that I appreciate the contributions of boost, I just hope that all
these macros never make the standard.

The best I could come up with, that compiles and runs correctly is
this:

#include <algorithm>
#include <iostream>
#include <vector>

template < typename T >
class Vector
{
private:
typedef std::vector< T > vec_type;

std::vector< T > realVec;
public:
typedef typename vec_type::const _iterator const_iterator;
typedef typename vec_type::size_ type size_type;

void reserve( size_type sz )
{
realVec.reserve ( sz );
}

size_type size() const
{
return realVec.size();
}

const_iterator begin() const
{
return realVec.begin() ;
}

const_iterator end() const
{
return realVec.end();
}

void push_back( const T& t )
{
return realVec.push_ba ck( t );
}
};

template < typename U, typename V, typename W >
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )
{
Vector<W> wvec;
typename Vector<U>::cons t_iterator uIter = uvec.begin();
typename Vector<U>::cons t_iterator uEnd = uvec.end();
typename Vector<V>::cons t_iterator vIter = vvec.begin();

wvec.reserve( uvec.size() );
while ( uIter != uEnd )
{
wvec.push_back( *uIter + *vIter );
++uIter;
++vIter;
}
return wvec;
}

template < typename T >
void outputVec( const Vector<T> & t )
{
std::copy( t.begin(), t.end(), std::ostream_it erator< T >(
std::cout, "\n" ) );
}

template < typename U, typename V >
void outputVecSum( const Vector<U> & uvec, const Vector<V> & vvec )
{
outputVec( vecSum( uvec, vvec, U() + V() ) );
}

int main()
{
Vector< int > uvec;
Vector< double > vvec;

uvec.push_back( 1 );
uvec.push_back( 2 );
uvec.push_back( 3 );

vvec.push_back( 1.5 );
vvec.push_back( 2.5 );
vvec.push_back( 3.5 );

outputVecSum( uvec, vvec );
}

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).

Jan 19 '06 #14
> template < typename U, typename V, typename W >
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).


this is cool, but to get a sum, we have to pass a 3rd argument, right?
So basically we cannot implement operator= without using a 3rd
parameter in these terms?

Jan 20 '06 #15
> template < typename U, typename V, typename W >
Vector<W> vecSum( const Vector<U> & uvec, const Vector<V> & vvec, W w )

Note I made every effort never to work out what type W would be (thus
outputVec and outputVecSum as templates).


this is cool, but to get a sum, we have to pass a 3rd argument, right?
So basically we cannot implement operator= without using a 3rd
parameter in these terms?

Jan 20 '06 #16
Earl Purple wrote:
an**@servocomm. freeserve.co.uk wrote:
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


Much that I appreciate the contributions of boost, I just hope that all
these macros never make the standard.


Boost.Typeof cant be anything but a macro for now. AFAIK The author is
fully aware that its only standing in for proper language support. IOW
its a macro exactly because the facilities it provides are not in the
standard. Notwithstanding that its a masterpiece IMO. Unfortunately it
is only available from boost cvs at the monent. I'm not sure if it
will make the next boost distro or not, but I hope it does.

regards
Andy Little

Jan 20 '06 #17
I didn't check CVS, but the file I'm currently using has this in the
comments so it sounds like what Andy is talking about.

"Return Type Deduction
[JDG Sept. 15, 2003]

Before C++ adopts the typeof, there is currently no way to deduce the
result type of an expression such as x + y. This deficiency is a major
problem with template metaprogramming ; for example, when writing
forwarding functions that attempt to capture the essence of an
expression inside a function."

I use it for the exact same purpose as the OP like so:

template <typename T0, typename T1>
typename boost::result_o f_plus<vec3<T0> , vec3<T1> >::type
operator+(vec3< T0> lhs, const vec3<T1> &rhs);

which is slightly different than your usage, but only because I
specialized the result_of struct on my type. I too hope this makes it
into the next boost distro.

Jan 20 '06 #18

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

Similar topics

35
4549
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
17879
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
2746
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
2626
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
1750
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
9425
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
10225
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
9867
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
7415
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
6676
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
5312
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...
1
3969
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
3573
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2816
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.