473,653 Members | 3,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arithmetic conversions/promotion and templates

Let me use complex numbers as a familiar example. The following is
taken verbatim from Bjarne Stroustrup, "The C++ Programming Language",
except the include line and the "no match" comments. It won't compile.

#include <complex>

// section 22.5:
// Throughout this book, I have used complex as a class rather than as a
// template. This is feasible because I assumed a bit of namespace magic to
// get the complex of double that I usually prefer:
typedef std::complex<do uble> complex;

// section 11.3:
// For example, from looking at a math textbook we would expect this to
work:
void f()
{
complex a = complex(1,2);
complex b = 3;
complex c = a+2.3;
complex d = 2+b; // no match for `int + complex&' operator
complex e = -b-c;
b = c*2*c; // no match for `complex& * int' operator
}

(Obviously we could kludge it by replacing 2 by 2.0 or double(2) etc.,
but I think we rightfully expect it to work exactly as Stroustrup wrote it.)

Questions: What was the rationale for implementing the standard library
like this?
Is there a generic way to accept any type that the usual arithmetic
conversions (C.6.3) can promote to double as the left or right argument
to a binary operator?

(I tried templating on the "simple" type, but when I do it for the left
and right argument, a+b becomes ambiguous. -- I there a way to express
that a template parameter "class T" must have a conversion to double?)

Thanks

Christian

Jul 19 '05 #1
3 2395
"Christian Brechbühler" <c_************ @yhaoo.com> wrote...
Let me use complex numbers as a familiar example. The following is
taken verbatim from Bjarne Stroustrup, "The C++ Programming Language",
except the include line and the "no match" comments. It won't compile.

#include <complex>

// section 22.5:
// Throughout this book, I have used complex as a class rather than as a
// template. This is feasible because I assumed a bit of namespace magic to // get the complex of double that I usually prefer:
typedef std::complex<do uble> complex;

// section 11.3:
// For example, from looking at a math textbook we would expect this to
work:
void f()
{
complex a = complex(1,2);
complex b = 3;
complex c = a+2.3;
complex d = 2+b; // no match for `int + complex&' operator
complex e = -b-c;
b = c*2*c; // no match for `complex& * int' operator
}

(Obviously we could kludge it by replacing 2 by 2.0 or double(2) etc.,
but I think we rightfully expect it to work exactly as Stroustrup wrote it.)
Questions: What was the rationale for implementing the standard library
like this?
This is a question for comp.std.c++. They discuss the "why" questions.
We here discuss the "how".
Is there a generic way to accept any type that the usual arithmetic
conversions (C.6.3) can promote to double as the left or right argument
to a binary operator?
Yes.

#include <complex>

typedef std::complex<do uble> complex;

template<class T>
complex operator +(const complex& c, T t) {
return std::operator +(c,complex(t)) ; // call the std:: one
}

void foo() {
complex a(1,2);
complex b = 2 + a; // ours works fine
}


(I tried templating on the "simple" type, but when I do it for the left
and right argument, a+b becomes ambiguous. -- I there a way to express
that a template parameter "class T" must have a conversion to double?)


I am not sure what you're saying here. Please supply the code.

Victor
Jul 19 '05 #2
Christian Brechbühler wrote:
Questions: What was the rationale for implementing the standard library
like this?
I don't know.
Is there a generic way to accept any type that the usual arithmetic
conversions (C.6.3) can promote to double as the left or right argument
to a binary operator?

(I tried templating on the "simple" type, but when I do it for the left
and right argument, a+b becomes ambiguous. -- I there a way to express
that a template parameter "class T" must have a conversion to double?)


I think you may need to be more generic with your example because
you can supply your own operators that solves the complex problem.

template <typename T>
inline complex<T> operator+ (
const typename complex<T>::val ue_type & r,
const complex<T> & c
)
{
return complex<T>( r, 0 ) + c;
}

template <typename T>
inline complex<T> operator* (
const complex<T> & c,
const typename complex<T>::val ue_type & r
)
{
return c * complex<T>( r, 0 );
}

Jul 19 '05 #3
Victor Bazarov wrote:
"Christian Brechbühler" <c_************ @yhaoo.com> wrote...
Is there a generic way to accept any type that the usual arithmetic
conversions (C.6.3) can promote to double as the left or right argument
to a binary operator?

Yes.

#include <complex>

typedef std::complex<do uble> complex;

template<class T>
complex operator +(const complex& c, T t) {
return std::operator +(c,complex(t)) ; // call the std:: one
}

void foo() {
complex a(1,2);
complex b = 2 + a; // ours works fine
}


Cool, thanks! I see it works, but how? With T=int, your definition
explicitly defines the operator complex + int. But apparently at the
same time it defines int + complex!
Your definition supports 2 + a and a + 2. Why?

I had tried something that looks superficially the same, except it
doesn't use typedef:

#include <complex>

template<class T, class Real>
std::complex<Re al> operator +(const std::complex<Re al>& c, T t) {
return std::operator +(c,std::comple x<Real>(t));
}

void foo() {
std::complex<do uble> a(1,2);
std::complex<do uble> b = 2 + a; // error: no match
std::complex<do uble> c = a + 2;
}

And here only one of the operators gets defined.

Thanks again to Victor for the quick and neat answer!

Christian

Jul 19 '05 #4

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

Similar topics

2
3635
by: Dan Stromberg | last post by:
Is there already a pure python module that can do modular-arithmetic unit conversions, like converting a huge number of seconds into months, weeks... or a bandwidth measure into megabits/s or gigabits/s or megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? Thanks!
10
2261
by: Niels Dekker (no reply address) | last post by:
Is it possible for a standard compliant C++ compiler to have ( sizeof(short) < sizeof(int) ) and ( sizeof(short) == sizeof((short)0 + (short)0) ) ? Regards, Niels Dekker http://www.xs4all.nl/~nd/dekkerware
22
12725
by: Alex Fraser | last post by:
From searching Google Groups, I understand that void pointer arithmetic is a constraint violation, which is understandable. However, generic functions like qsort() and bsearch() must in essence do exactly this, and similarly generic functions seem to have useful applications. In a few posts I read, it was suggested to avoid void pointer arithmetic by casting to a char pointer, and performing arithmetic on that (in multiples of...
16
5117
by: TTroy | last post by:
Hello, I'm relatively new to C and have gone through more than 4 books on it. None mentioned anything about integral promotion, arithmetic conversion, value preserving and unsigned preserving. And K&R2 mentions "signed extension" everywhere. Reading some old clc posts, I've beginning to realize that these books are over-generalizing the topic. I am just wondering what the difference between the following pairs of terms are: 1)...
21
4105
by: Frederick Gotham | last post by:
I set about trying to find a portable way to set the value of UCHAR_MAX. At first, I thought the following would work: #define UCHAR_MAX ~( (unsigned char)0 ) However, it didn't work for me. Could someone please explain to me what's going on? I would have thought that the following happens: (1) The literal, 0, whose type is int, gets converted to an unsigned char.
2
5116
by: Frederick Gotham | last post by:
I just want to clarify my understanding of arithmetic and comparison between two different integer types. Phase (1): Integer Promotion ---------- All of the following types always get promoted to "signed int": signed char
6
13814
by: sarathy | last post by:
Hi, What is integer promotion? How is it different from arithmetic conversion? Regards, Sarathy
9
2422
by: Joe Cool | last post by:
Hello, I am using VS2005. I am trying to convert a VB.NET app to C#.NET. The VB app uses a progress meter to indiate how far a file has been read. I use the following assignment statement in VB: Progress.Value = (lFileReadCount / fi.Length) * 100 lFileReadCount is a Long that contains the current number of bytes read. fi is a FileInfo object of the file being read. Progress is shown as a percentage.
1
1142
by: dizzy | last post by:
Hello I have noticed a strange behavior (tho for many of you this is to be expected I'm sure :) ) when I have an expression that adds a long value with an unsigned one (like in "10l + 10u"). On 32bit platforms (where unsigned can represent more than long) the result is of unsigned long type while on 64bit platforms the result is of long time.
0
8370
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
8283
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
8811
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
8470
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
7302
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
6160
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...
1
2707
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
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
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.