473,795 Members | 3,122 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading operators using templates...

I was wondering if someone could help me get around this problem I'm
having. I'm writing a fraction class and would like to overload the
binary arithmetic operators so that when any numerical data type (int,
double, long double, etc.) is used with a fraction it is first
converted to a fraction and then added, the result being a fraction.

So I started with this:

template <class numericType>
friend fraction operator +(const fraction& lhs, const numericType&
rhs);
template <>
friend fraction operator +(const fraction& lhs, const fraction& rhs);

The first function was simply:

{ return lhs + fraction(rhs); }

The second function was a template specialization that did the math
when adding two fractions. This worked great, as long as a fraction
was the first argument I could add it with any other data type that I
had a constructor for. But I also want addition to be commutative so
that "fraction + int" and "int + fraction" do the same thing. To get
that I added this function:

template <class numericType>
friend fraction operator +(const numericType& lhs, const fraction&
rhs);

Which did the same thing as the other function, converted explicitly to
a fraction and then added, relying on the template specialization to
add fractions. But now I get this error:

error C2667: '+' : none of 2 overload have a best conversion

How can I get rid of this? I just want it so that given:
fraction x, y;
int z;

these statements are valid and error free:

x + y;
x + z;
z + x;

I'm running VC++ 6.0

Jul 23 '05 #1
3 2454
Starx wrote:
I was wondering if someone could help me get around this problem I'm
having. I'm writing a fraction class and would like to overload the
binary arithmetic operators so that when any numerical data type (int,
double, long double, etc.) is used with a fraction it is first
converted to a fraction and then added, the result being a fraction.

So I started with this:

template <class numericType>
friend fraction operator +(const fraction& lhs, const numericType&
rhs);
template <>
friend fraction operator +(const fraction& lhs, const fraction& rhs);

The first function was simply:

{ return lhs + fraction(rhs); }

The second function was a template specialization that did the math
when adding two fractions. This worked great, as long as a fraction
was the first argument I could add it with any other data type that I
had a constructor for. But I also want addition to be commutative so
that "fraction + int" and "int + fraction" do the same thing. To get
that I added this function:

template <class numericType>
friend fraction operator +(const numericType& lhs, const fraction&
rhs);

Which did the same thing as the other function, converted explicitly to
a fraction and then added, relying on the template specialization to
add fractions. But now I get this error:

error C2667: '+' : none of 2 overload have a best conversion

How can I get rid of this? I just want it so that given:
fraction x, y;
int z;

these statements are valid and error free:

x + y;
x + z;
z + x;

I'm running VC++ 6.0


If class 'fraction' has constructors for each of the
required numeric types (fraction(int), fraction(long),
fraction(double ), etc), then you should only need one
friend operator+() method that takes 2 'fraction'
objects. If a numeric is specified on either side
of the "+" (z + x, or x + z), the compiler should
apply the correct conversion constructor before
invoking the operator+().

Here's an example:

#include <iostream>

// a dummy 'fraction' class for experimental purposes
class fraction
{
public:
fraction() : vd(0) {}
fraction(const int v) : vd(v) {}
fraction(const long v) : vd(v) {}
fraction(const double v) : vd(v) {}

fraction operator=(const fraction& oth)
{ vd = oth.vd; vi = oth.vi; }

friend fraction operator+(const fraction& rhs, const fraction& lhs);

int vi;
double vd;
};
fraction operator+(const fraction& rhs, const fraction& lhs)
{ return fraction(rhs.vd + lhs.vd); }

int main()
{
fraction fx(25.34), fy(30), fr;
int iz = 66;
long lz = 530;

std::cout << "fx = " << fx.vd << ", "
<< "fy = " << fy.vd << ", "
<< "iz = " << iz << ", "
<< "lz = " << lz << std::endl;

fr = fx + fy;
std::cout << "fx + fy = " << fr.vd << std::endl;

fr = fx + iz; // 'iz' is converted to a 'fraction'
std::cout << "fx + iz = " << fr.vd << std::endl;

fr = iz + fx; // 'iz' is converted to a 'fraction'
std::cout << "iz + fx = " << fr.vd << std::endl;

fr = lz + fx; // 'lz' is converted to a 'fraction'
std::cout << "lz + fx = " << fr.vd << std::endl;

fr = 99 + fy; // 99 is converted to a fraction
std::cout << "99 + fy = " << fr.vd << std::endl;

fr = fy + 99; // 99 is converted to a fraction
std::cout << "fy + 99 = " << fr.vd << std::endl;

return 0;
}

Regards,
Larry
Jul 23 '05 #2
Larry I Smith wrote:
[snip]

If class 'fraction' has constructors for each of the
required numeric types (fraction(int), fraction(long),
fraction(double ), etc), then you should only need one
friend operator+() method that takes 2 'fraction'
objects. If a numeric is specified on either side
of the "+" (z + x, or x + z), the compiler should
apply the correct conversion constructor before
invoking the operator+().

[snip]

Don't forget to include constructors for any required
unsigned types, e.g.: fraction(unsign ed int), etc.

Larry
Jul 23 '05 #3
My constructor is flagged with the explicit keyword. I did this
because I was also trying to overload the pow function. I wanted to
write different versions for fraction and int powers to optimize the
way it did the math, but if I don't make the constructor explicit it
says those version are ambiguous.

Jul 23 '05 #4

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

Similar topics

4
6490
by: Dave Theese | last post by:
Hello all, I'm trying to get a grasp of the difference between specializing a function template and overloading it. The example below has a primary template, a specialization and an overload. Note that the overload is identical to the specialization except, of course, for the missing "template <>". I don't know if my questions will be a bit too broad or not, but I thought I'd give it shot... When is overloading preferable to...
2
3582
by: Marcin Vorbrodt | last post by:
I see a lot of source code where some operators are defined as class members, and some as friends, or just outside the class. Can someone please explain what the general rule of thumb is? I understand that operators like == or != can/should be definced outside of the class in order to be symetric. What about all the other ones? I read somewhere that only the operators that need to modify theri lvalue should be members... what are those...
2
2276
by: bq | last post by:
Hello, This post is really two questions. Question 1: What is the current status on a revision of ISO C++, specifically regarding plans for overloading composite operators? Some people in this group probably would know. By "overloading composite operators" I mean conversion of an expression like A = B * C; into a single function call (instead of three calls; one to "*", another to copy and another to "="). Here A, B and C are of a
20
1847
by: KL | last post by:
I am working on a school assignment, so please don't tell me the solution. I just want some direction. I am supposed to overload the >, <, ==, !=, >=, and <= operators using bool. I am having a bit of a problem in seeing what needs to happen here. I am just not sure how I do this. Will the overloading function recognize a < and a usual <? Do I do an IF (a.letters < b.letters){ return true }
6
5423
by: TuxC0d3 | last post by:
Hi! I'm diving into the some more ++ specific aspects of c++ (and finally accepting that c++ is more than "a plus added to c" :), so that means using namespaces, templates, std::strings, lists, vectors, operator overloading and what not.. And i was wondering if there is a way to override the global dereference operator, so to be able to check the address that one tries to dereference. This gives the ability to throw an exception when...
2
2920
by: allan.mcrae | last post by:
I am having trouble with overloading the += operator when template parameters are used. I have a class holding an array (called "derived" in the following example) which derives from a base class ("base"). I want to be able to add: 1) any derived array holding class to any other derived array holding class 2) any derived array holding class to a literal value (e.g int, double, etc) for which addition is defined for the type in the...
11
1977
by: Zilla | last post by:
I have the following simple program. I just want to be able to do math operations (+, -, =)on Timer sublcasses, but want to handle cases where either rhs or lhs is an intrinsic value, However, the compile fails in my g++ 2.95 compiler during the 2nd to last line of the main() with template.cpp: In function `int main()': template.cpp:24: `operator +<int>(int, const int &)' must have an argument of class or enumerated type template.cpp:...
8
2977
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular, operator =, operator, operator(), and operator-must be nonstatic member function; this ensures that their first operands will be lvalues". I know that these operators must be nonstatic member functions, but why this ensure their first operands will...
30
340
by: none | last post by:
I'm trying to overload the = operator using templates, but I have some problems with one of the overloads, I would like to make something like that: intvariable = fooclass; here's a pseudo code of what I'm doing: template <class COMPLEXTYPE> class foo
2
2952
by: jimzat | last post by:
I am trying to simulate the execution of some PLC ladder logic in python. I manually modified the rungs and executed this within python as a proof of concept, but I'd like to be able to skip the modification step. My thought was that this might be able to be completed via overloading, but I am not sure if (or how) it could be done. overloadings: + ==OR
0
9672
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...
1
10165
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
10001
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
9043
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
7541
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
6783
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
4113
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
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.