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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With