1
using System.Collections;
using System;

public class Counter<T>
{
    private int pivot = 0;
    private readonly int arraySize = 256;
    private bool startCheck = false;

    T[] baskets;

    public T Count
    {
        get
        {
            return baskets[pivot];
        }
    }

    public void CountPlus(T plusValue)
    {
        if(!startCheck)
        {
            startCheck = true;

            baskets[pivot] = plusValue;
        }
        else
        {
            int previousPivot = pivot;

            pivot++;

            if( previousPivot == arraySize - 1 )
            {
                pivot = 0;
            }

            checked
            {
                try
                {
                    baskets[pivot] = baskets[previousPivot] + plusValue;
                }
                catch(OverflowException ofe)
                {
                    Debug.Log("=*=*=*=*=*=*=*=*= OverflowException =*=*=*=*=*=*=*=*=*=");
                }
            }

        }
    }
}

Hello~

I want to run this code but i have got an error message

error CS0019: Operator '+' cannot be applied to operands of type 'T' and 'T'

How do I solve this error?

crthompson
  • 15,653
  • 6
  • 58
  • 80
  • `T` could be any type. What if it's a Person object, how do you add them together? The short answer is, there doesn't appear to be any easy way to constrain `T` to be a numeric type. See: http://stackoverflow.com/questions/32664/c-sharp-generic-constraint-for-only-integers – Evan Trimboli Oct 30 '13 at 05:17
  • I don't think you can. It would require a constraint on T requiring it to have a plus operator, and as far as I know that's not possible. – Alxandr Oct 30 '13 at 05:17
  • you can check this link: http://stackoverflow.com/questions/1251507/is-it-possible-to-call-value-type-operators-via-reflection – Victor Mukherjee Oct 30 '13 at 05:29

3 Answers3

1

You could use dynamic:

dynamic o1 = baskets[previousPivot];
dynamic o2 = plusValue;
baskets[pivot] = o1 + o2;

Then code like this works:

Counter<int> intCounter = new Counter<int>();
intCounter.CountPlus(3);
intCounter.CountPlus(5);

Counter<double> doubleCounter = new Counter<double>();
doubleCounter.CountPlus(2.1);
doubleCounter.CountPlus(3.8);
stames
  • 1,250
  • 1
  • 10
  • 16
0

If you're sure that T is always going to be an int, cast your T to an int.

baskets[pivot] = ((int)baskets[previousPivot]) + (int)plusValue;

However, if T is always going to be an int, it doesnt make much sense to have it generic.

crthompson
  • 15,653
  • 6
  • 58
  • 80
-1

There is a library for generic operators.

Jason L
  • 510
  • 5
  • 16