Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations on arbitrary value types

This article describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code:

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

This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this:

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 see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types.

Update: For .NET, Marc Gravell has made a utility library which solves the operator problem very elegantly.

like image 743
Morten Christiansen Avatar asked Oct 21 '08 13:10

Morten Christiansen


2 Answers

Due to the way templates are compiled in C++, simply doing:

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

will work, you'll get a compile error for every type where an operator+ is not defined.

C++ templates generate code for every type instantiation, so for every type T code will be generated that does the right thing. This way C++ doesn't need Num<> trickery.

In plain C, this is not possible as far as I know.

like image 191
Pieter Avatar answered Sep 29 '22 01:09

Pieter


In C++ this is simply not an issue. The code as in your first sample works if literally translated into C++ (ETA: as Pieter did), but I can't think of any situation where directly using + wouldn't work. You're looking for a solution to a problem that doesn't exist.

like image 31
Leon Timmermans Avatar answered Sep 28 '22 23:09

Leon Timmermans