【问题标题】:Convert template to generic将模板转换为泛型
【发布时间】:2014-02-13 17:52:12
【问题描述】:

考虑一下 C++/CLI 中的这个简单代码

template <typename T>
T sum (T x, T y)
{
    return x + y;
}

int main(array<System::String ^> ^args)
{
    int a=4, b=6;
    double x=2.3, y=5.2;

    Console::WriteLine("Sum of two ints = {0}", sum(a, b));
    Console::WriteLine("Sum of two doubles = {0}", sum(x, y));

    return 0;
}  

输出:

Sum of two ints = 10
Sum of two doubles = 7.5

如何在 C# 中使用泛型做到这一点?

【问题讨论】:

标签: c# templates generics c++-cli


【解决方案1】:

你不能。没有办法在 C# 中应用泛型约束来确保给定的泛型类型将具有适当的 + 运算符重载。

您可以删除所有静态类型检查并使用反射或类似于 尝试 在运行时调用给定泛型类型的 + 运算符,意识到如果没有,它将简单地抛出运行时异常适用的运算符存在,但不等同于您提供的 C++ 代码。

【讨论】:

    【解决方案2】:

    使用泛型没有简单的方法,因为泛型不是模板。如果您自己提供运算符,则可以这样做,如下所示:

    static T binary_apply<T>(T a, T b, Func<T,T,T> add) {
        return add(a, b);
    }
    
    int a = 4, b = 6;
    double x = 2.3, y = 5.2;
    Console.WriteLine("Sum of two ints = {0}", binary_apply(a, b, (i,j)=>i+j));
    Console.WriteLine("Sum of two doubles = {0}", binary_apply(x, y, (i,j)=>i+j));
    

    当然,这首先违背了使用add&lt;T&gt;() 的目的,因为您将加法的实现作为 lambda 传递。您也可以动态执行此操作,但这与编译器解析添加不同:

    static T add<T>(T a, T b) {
        var p0 = Expression.Parameter(typeof(T));
        var p1 = Expression.Parameter(typeof(T));
        var ae = Expression.Add(p0, p1);
        var f = (Func<T,T,T>)Expression.Lambda(ae, p0, p1).Compile();
        return f(a, b);
    }
    
    int a = 4, b = 6;
    double x = 2.3, y = 5.2;
    Console.WriteLine("Sum of two ints = {0}", add(a, b));
    Console.WriteLine("Sum of two doubles = {0}", add(x, y));
    

    Demo on ideone.

    【讨论】:

    • 感谢您的演示。但是,两个问题 1)方法 add 必须是静态的? 2)什么是表达。界面?抽象类?我在哪里可以研究这些东西?谢谢。
    • @user3307184 (1) static C# 的函数最接近 C++ 的“独立”函数。如果必须,您可以使函数成为非静态函数,但在这种情况下,它会使事情变得不必要地复杂化。 (2) Expression 是一个 LINQ 类,可让您在运行时构建表达式。 Here is a link to its documentation.
    • 再次感谢。你的回答很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多