473,830 Members | 2,294 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to handle int and float in one class

Lee
I'd like to implement a generic class that takes as its Type-parameter
a numeric type (e.g. (U)Int16/32/64, float, double, decimal, etc.).

The problem is that, having validated the Type-parameter, I cannot do
any arithmetic operations (+, -, *, /) on variables of that type.

I tried creating wrapper-classes for the numeric types I will support
and tried to derive them from a custom interface that specified the
above 4 operators -- but interfaces are not allowed to specify
operators.

The only solution I can think of is to use a 'switch' statement at the
places I need to do the arithmetic operations -- but to me that is a
very poor solution.

I'm fairly sure this problem has arisen before and I'm hoping someone
can point me to a viable solution.

--
Lee Silver
Information Concepts Inc.
Jul 4 '08 #1
6 1858
Lee wrote:
I'd like to implement a generic class that takes as its Type-parameter
a numeric type (e.g. (U)Int16/32/64, float, double, decimal, etc.).

The problem is that, having validated the Type-parameter, I cannot do
any arithmetic operations (+, -, *, /) on variables of that type.

I tried creating wrapper-classes for the numeric types I will support
and tried to derive them from a custom interface that specified the
above 4 operators -- but interfaces are not allowed to specify
operators.
I'm fairly sure this problem has arisen before and I'm hoping someone
can point me to a viable solution.
You need to use an abstract base class or (preferably) an interface that
defines the operations you want as methods. You can't do it just with
operators.

The general pattern is the same as with IComparer<Tand
IEqualityCompar er<T- these provide equivalents of '<' and '=='
respectively, in the form of Compare and Equals, respectively.

You then pass an implementation of your IArithmetic<Tto your generic
class's constructor, or methods that require such operations. If you do
it right, you can even avoid virtual / interface method calls:

---8<---
using System;

interface IArithmetic<T>
{
T Add(T l, T r);
}

struct Int32Arithmetic : IArithmetic<int >
{
public int Add(int l, int r) { return l + r; }
}

class App
{
static T Sum<T,TOps>(T[] array, TOps ops)
where TOps: IArithmetic<T>
{
T result = default(T);
foreach (T item in array)
result = ops.Add(result, item);
return result;
}

static void Main()
{
int[] values = { 10, 20, 30 };
Console.WriteLi ne(
Sum<int,Int32Ar ithmetic>(value s,
new Int32Arithmetic ()));
}
}
--->8---

The calls to ops.Add above are resolved statically due to (1) TOps being
constrained to an interface, (2) the implementation type specified
directly, and (3) the concrete implementation of the interface being on
a sealed type, such as a struct.

Obviously, if you're doing lots of this, you'll want to specify TOps &
ops in a descendant class & constructor, to avoid verbosity.

With appropriate reflection tricks, an equivalent to Comparer<T>.Def ault
(that might be called Arithmetic<T>.D efault, for example) can be
created.

-- Barry

--
http://barrkel.blogspot.com/
Jul 4 '08 #2
On Jul 4, 5:15*am, Lee <lsil...@inform ation-concepts.comwro te:
I'd like to implement a generic class that takes as its Type-parameter
a numeric type (e.g. (U)Int16/32/64, float, double, decimal, etc.).

The problem is that, having validated the Type-parameter, I cannot do
any arithmetic operations (+, -, *, /) on variables of that type.
You'd probably find the Operator class in MiscUtil useful. MiscUtil is
a free library I've got: http://pobox.com/~skeet/csharp/miscutil

The Operator class is written by Marc Gravell.

See http://pobox.com/~skeet/csharp/miscu...operators.html
for more details.

Jon
Jul 4 '08 #3
Lee
On Jul 4, 1:56 pm, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
On Jul 4, 5:15 am, Lee <lsil...@inform ation-concepts.comwro te:
I'd like to implement a generic class that takes as its Type-parameter
a numeric type (e.g. (U)Int16/32/64, float, double, decimal, etc.).
The problem is that, having validated the Type-parameter, I cannot do
any arithmetic operations (+, -, *, /) on variables of that type.

You'd probably find the Operator class in MiscUtil useful. MiscUtil is
a free library I've got:http://pobox.com/~skeet/csharp/miscutil

The Operator class is written by Marc Gravell.

Seehttp://pobox.com/~skeet/csharp/miscutil/usage/genericoperator s.html
for more details.

Jon
Jon:

Thanks for the response.

I found the links you mentioned after posting my message (my bad for
not doing a more thorough search ahead of time :) -- I was about to
post that I found the ones you cited when I saw your response.)

Anyway, they are exactly what I am looking for.

Much thanks.

--
Lee Silver
Information Concepts Inc.
Jul 4 '08 #4
If you get any problems, let me know; I also have a 2.0 version
somewhere, but it isn't as complete nor unit tested.

Marc
Jul 4 '08 #5
On Jul 4, 8:04*am, Marc Gravell <marc.grav...@g mail.comwrote:
If you get any problems, let me know; I also have a 2.0 version
somewhere, but it isn't as complete nor unit tested.
We ought to do something about this - and the fact that it's currently
in MiscUtil, despite being a clearly desirable entity in its own
right. I think it may be time to start thinking about a
code.google.com project just for the operator stuff. The reason I'm
posting this instead of mailing it straight to Marc is that it would
be good to get more people involved. Quite how we then migrate it
*out* of MiscUtil is a different question, but we can tackle that
later.

Jon
Jul 4 '08 #6
No problem here; my only thought is that there isn't really much left to
do with it now (I can't envisage any huge changes / feature requests) so
it would mainly be a code dump, not an active project.

I like the employer-loyalty, though; last time we discussed this
(probably re the whole of MiscUtil), I'm sure you were talking about
another code site ;-p

Marc
Jul 4 '08 #7

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

Similar topics

8
3567
by: Grant Edwards | last post by:
Perhaps I'm doing something wrong: the struct module docs say it's IEE 754, but I can't figure out how to get it to handle NaN values correctly (either packing or unpacking). >>> x = float('nan') >>> struct.pack("<f",x) Traceback (most recent call last): File "<stdin>", line 1, in ? SystemError: frexp() result out of range
6
2812
by: TJ | last post by:
I've got a calendar that is based on the concept of lots of blocks that are spans with float:left. I would like to be able to have a detail section on the right side of the screen, so that when the user selects an item on the calendar, the detail can get displayed on the right side there. What I have below appears to look perfect in mozilla based browsers - the detail is aligned at the top right corner of the calendar, but in IE the...
7
1870
by: Ben | last post by:
Hi all, I'm not yet good at thinking the right way in c++ so although I could solve this problem, I'm not sure if they way I'm thinking of is the best way to do it. I need a data type or class or something that can hold either an int, or a float, knows which one it is holding, and will allow me to do comparisons with instances of it without the code which asks for the comparison having to know which one it is. So maybe I could do it...
14
2727
by: Glen Able | last post by:
Should it be possible to create a custom class, 'Float', which would behave as a drop-in replacement for the builtin float type? As mentioned in another thread, I once tried this in rather a hurry to try and catch some floating point naughtiness, but was stumped in various places. Is there a fundamental obstacle to doing this? thanks, G.A.
5
7260
by: john smith | last post by:
Hi, I am trying to initialize a float in a class. For example: class ABC{ public:
3
3459
by: Sybren Stuvel | last post by:
Hi all, I'm trying to make a float-like class (preferably a subclass of 'float') that wraps around. The background: I'm modeling a multi-dimensional space, and some of those dimensions are circular. Here is my code so far: class WrapFloat(float): def __init__(self, value, wrap = None):
5
4177
by: Mr. Ken | last post by:
I am calculating the phase of an IQ signal, which are polluted by AWGN gaussian noise. Thus, near pi/2, direct division of atan(Q/I) may yield outputs either +pi/2 or -pi/2. How do I handle this situation? Thanks.
3
3758
by: shapper | last post by:
Hello, I was reading an article and I can't figure something. I have: div.float { float: left; } And the HTML:
27
3918
by: GloStix | last post by:
WARNING VIDEO TAKES A WHILE TO LOAD http://screencast.com/t/BWQ6DNtsM I really don't know how to fix this other than putting another div. But I dont' exactly want to do that for every page. random div's everywhere Is there any other way? Also I'm trying to get a scaled thumbnail of the orginal picture WHILE maintaining the size of the css box.. Is that possible? Or do I have to scale it in Photoshop and make a separate image =\
0
9793
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
10774
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
10489
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
10525
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
9314
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...
0
6950
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
5780
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3076
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.