首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >对任意值类型的操作

对任意值类型的操作
EN

Stack Overflow用户
提问于 2019-06-10 01:14:45
回答 2查看 0关注 0票数 0

这,这个文章描述一种在C#中允许添加具有为它们定义的+运算符的任意值类型的方法。本质上,它允许以下代码:

代码语言:txt
复制
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:

代码语言:txt
复制
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.

EN

回答 2

Stack Overflow用户

发布于 2019-06-10 10:10:54

这可以很容易地在C+中使用模板完成:

代码语言:txt
复制
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.

票数 0
EN

Stack Overflow用户

发布于 2019-06-10 10:25:07

在C+中,这根本不是一个问题。与第一个示例中的代码一样,如果真的将代码转换为C+(ETA:Pieter那样),那么代码就能工作,但是我想不出任何直接使用+的情况都是行不通的。你在寻找一个不存在的问题的解决方案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档