473,387 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 1842
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
IEqualityComparer<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.WriteLine(
Sum<int,Int32Arithmetic>(values,
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>.Default
(that might be called Arithmetic<T>.Default, for example) can be
created.

-- Barry

--
http://barrkel.blogspot.com/
Jul 4 '08 #2
On Jul 4, 5:15*am, Lee <lsil...@information-concepts.comwrote:
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.comwrote:
On Jul 4, 5:15 am, Lee <lsil...@information-concepts.comwrote:
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/genericoperators.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...@gmail.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
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 =...
6
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...
7
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...
14
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...
5
by: john smith | last post by:
Hi, I am trying to initialize a float in a class. For example: class ABC{ public:
3
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...
5
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...
3
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
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....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.