0

想象一下我们有这样的东西(这只是一个例子)

public interface Foo : GLib.Object {
    public abstract double *f();
}

public class Toto : GLib.Object, Foo {

    private double i;

    public Toto(double i = 0) {
        this.i = i;
    }

    public double *f() {
        return &i;
    }

    public static int main(string[] args) {
        Foo a = new Toto(42.0);
        double i = *a.f();
        stdout.printf("%.3f\n", i);
        return 0;
    }
}

这段代码工作得很好,但问题是它Foo必须是通用的public abstract T *f(),所以Toto必须实现Foo<double>,但是

`double' 不是受支持的泛型类型参数

(我的第一个问题是“为什么?”,据我所知,我可以使用 int 例如没有任何问题)

所以它是Foo<double?>,我需要类似的东西double i = (!) *(a.f()),但它只是不起作用(在 C 级别)

错误:无效表达式的使用无效i = (gdouble) (*(*_tmp1_));

那么我该如何使用f()方法呢?

(我的 vala 版本是 0.36.3)

4

1 回答 1

0

你为什么首先在 Vala 中使用指针?(这是不鼓励的,指针是用于极端情况的语言。)

Vala 中的可空类型是生成的 C 代码中的指针。

所以解决这个问题的一种方法是:

public interface Foo<T> : GLib.Object {
    public abstract T f();
}

public class Toto : GLib.Object, Foo<double?> {

    private double i;

    public Toto(double i = 0) {
        this.i = i;
    }

    public double? f() {
        return i;
    }

    public static int main(string[] args) {
        Foo<double?> a = new Toto(42.0);
        double? i = a.f();
        stdout.printf("%.3f\n", (!) i);
        return 0;
    }
}

这可以在此处与 valac 0.36.3 一起编译并完美运行。

生成的 C 函数的类型签名为Toto.f

static gdouble* toto_real_f (Foo* base);
于 2017-06-26T11:52:10.717 回答