我想为每个基本类型设置二维 vector 类。
现在,为了确保最佳的运行时性能并能够使用许多实用函数,我需要为每个基元(Vector2Int、Vector2Float、Vector2Long 等)创建一个单独的类。
这只是大量的复制粘贴,如果我必须进行更改,我必须记住在每个类和每个实用程序函数中都进行更改。
有没有什么可以让我编写类似 C++ 模板的东西(或者有什么方法可以创建它)?
我创建了一个小概念来向您展示它是如何工作的:
// compile is a keyword I just invented for compile-time generics/templates
class Vector2<T> compile T : int, float, double, long, string
{
public T X { get; set; }
public T Y { get; set; }
public T GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
}
}
// during compilation, code will be automatically generated
// as if someone manually replaced T with the types specified after "compile T : "
/*
VALID EXAMPLE (no compilation errors):
autogenerated class Vector2<int>
{
public int X { get; set; }
public int Y { get; set; }
public int GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
}
}
UNVALID EXAMPLE (build failed, compilation errors):
autogenerated class Vector2<string>
{
public string { get; set; } // ok
public string { get; set; } // ok
public string GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)); // error! string cannot be used with Math.Pow()
// and Math.Sqrt doesn't accept string type
}
}
*/
是否有一些聪明的方法来实现它,或者这完全不可能?
抱歉,我不是很清楚,但让我解释一下问题是什么。
考虑使用普通的 C# 泛型。 GetLength() 方法无法编译,因为我要使用的所有类型(int、float、double、long)都需要共享一个接口(interface),Math.Pow() 应该接受该接口(interface)作为参数。
从字面上用类型名称替换“T” token 将解决这个问题,增加灵 active ,达到手写代码性能并加快开发速度。
我制作了自己的模板生成器,它通过编写 C# 代码生成 C# 代码 :) http://www.youtube.com/watch?v=Uz868MuVvTY
最佳答案
不幸的是,C# 中的泛型与 C++ 中的模板有很大不同。为了实现这一点,共享接口(interface)(例如 IArithmetic
)必须存在 (which has been highly requested, but not implemented) * 用于不同的类型,现在不在框架中。
这可以通过代码生成和 T4 templates 来完成,但是,它需要根据共享的"template"为每种类型生成代码。
*注意:连接请求似乎被阻止,至少是暂时的。
关于c# - C# 中的 C++ 样式模板,以任何方式可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343095/