Operations on arbitrary value types

This article describes a method in C # that allows you to add arbitrary value types that have the + operator defined for them. Essentially, it allows you to use the following code:

public T Add(T val1, T val2)
{
   return val1 + val2;
}

This code does not compile, since there is no guarantee that type T has a definition for the + operator, but the effect is achieved using the code as follows:

public T Add(T val1, T val2)
{
   //Num<T> defines a '+' operation which returns a value of type T
   return (new Num<T>(val1) + new Num<T>(val2));
}

Follow the link to find out how the Num class achieves this. In any case, to the question. Is there a way to achieve the same effect in C or C ++? For the curious, the problem I'm trying to solve is to allow the CUDA core to be more flexible / general, allowing it to work with a lot of types.

:. .NET > , .

+5
5

- , ++, :

template < class T >
T add(T const & val1, T const & val2)
{
    return val1 + val2;
}

, , + .

++ , T , . , ++ Num < > trickery.

C , .

+13

++ . , , , ++ (ETA: Pieter), , + . , .

+4

++ :


template <typename T>
T Add(T val1, T val2)
{
  return val1 + val2;
}

, , , , , const .

C .

+1

C, , , .

#define ADD(A,B) (A+B)
+1

++. C, .

template<typename T> 
T add(T x, T y)
{ 
    return x + y;
}
0

All Articles