这,这个文章描述一种在C#中允许添加具有为它们定义的+运算符的任意值类型的方法。本质上,它允许以下代码:
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.
发布于 2019-06-10 10:10:54
这可以很容易地在C+中使用模板完成:
template <typename T>
T Add(T val1, T val2)
{
return val1 + val2;
}
Note, however, that this must在头文件中定义,您可能还希望通过Const引用而不是按值传递参数。
This cannot be done in plain C at all.
发布于 2019-06-10 10:25:07
在C+中,这根本不是一个问题。与第一个示例中的代码一样,如果真的将代码转换为C+(ETA:Pieter那样),那么代码就能工作,但是我想不出任何直接使用+的情况都是行不通的。你在寻找一个不存在的问题的解决方案。
https://stackoverflow.com/questions/-100001249
复制相似问题