对任意值类型的操作
这篇文章描述了一种在 C# 中允许添加任意值类型,并为其定义了 + 运算符。 本质上,它允许以下代码:
public T Add(T val1, T val2)
{
return val1 + val2;
}
此代码不会编译,因为不能保证 T 类型具有“+”运算符的定义,但效果是通过如下代码实现的:
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));
}
按照链接查看 Num 如何类实现了这一点。 不管怎样,还是回答这个问题吧。 有没有办法在C或C++中达到同样的效果? 出于好奇,我试图解决的问题是通过允许 CUDA 内核在更多类型上运行来使其更加灵活/通用。
更新: 对于 .NET,Marc Gravell 制定了 实用程序库非常优雅地解决了操作员问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于 C++ 中模板的编译方式,只需执行:
即可工作,对于未定义运算符+的每种类型,您都会收到编译错误。
C++ 模板为每个类型实例化生成代码,因此对于每个类型都会生成执行正确操作的 T 代码。 这样C++就不需要Num<>了。 诡计。
据我所知,在普通 C 中这是不可能的。
Due to the way templates are compiled in C++, simply doing:
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.
在 C++ 中,这根本不是问题。 如果将第一个示例中的代码字面翻译成 C++(预计到达时间:正如 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.
这可以在 C++ 中使用模板轻松完成:
但是请注意,此必须在头文件中定义,并且您可能还希望通过 const 引用而不是通过值传递参数。
这根本无法在普通 C 中完成。
This can easily be done in C++ using templates:
Note, however, that this must be defined in a header file, and you probably also want to pass the parameters by const reference instead of by value.
This cannot be done in plain C at all.
它也可以用 C 语言完成,尽管我不确定它是否满足问题要求,用宏。
It can be done in C as well, although I'm not sure it meets the problem requirements, with a Macro.
C++ 中的模板。
在 C 语言中,并非没有巨大的麻烦和开销。
Templates in C++.
In C, not without massive hassle and overhead.