【问题标题】:Vala interface generics compiler errorVala 接口泛型编译器错误
【发布时间】:2012-12-15 08:11:43
【问题描述】:

我有以下小例子(vala 0.18.1):

namespace Learning
{
   public interface IExample<T>
   {
      public abstract void set_to(T val);
      public abstract T get_to();
   }

   public class Example : Object, IExample<double>
   {
      private double to;

      public void set_to(double val)
      {
         to = val;
      }

      public double get_to()
      {
         return to;
      }

      public string to_string()
      {
         return "Example: %.5f".printf(to);
      }
   }

   public class Test
   {
      public static void main(string[] args)
      {
         stdout.printf("Start test\n");

         Example ex = new Example();

         stdout.printf("%s\n", ex.to_string());
         ex.set_to(5.0);
         stdout.printf("%s\n", ex.to_string());

         stdout.printf("End test\n");
      }
   }
}

这会引发错误:

/src/Test.vala.c: In function ‘learning_test_main’:
/src/Test.vala.c:253:2: error: incompatible type for argument 2 of ‘learning_iexample_set_to’
/src/Test.vala.c:117:6: note: expected ‘gconstpointer’ but argument is of type ‘double’
error: cc exited with status 256
Compilation failed: 1 error(s), 0 warning(s)

现在,根据我在 Vala 中的泛型接口上找到的少量文档,http://www.vala-project.org/doc/vala-draft/generics.html#genericsexamples,这应该可以工作。当我检查生成的 C 代码时,它显示 Example 的 set_to 函数采用 double 和 IExample 的 set_to 函数采用 gconstpointer。

那么为什么 main 函数会使用 gconstpointer 版本而不是 double 版本呢?有人可以向我解释为什么它不起作用以及解决它的方法吗?

感谢您的帮助。

附:是的,我知道找到的文档是草稿。

答案代码: 根据下面选择的答案,这就是我将代码更改为的内容。

namespace Learning
{
   public interface IExample<T>
   {
      public abstract void set_to(T val);
      public abstract T get_to();
   }

   public class Example : Object, IExample<double?>
   {
      private double? to;

      public void set_to(double? val)
      {
         to = val;
      }

      public double? get_to()
      {
         return to;
      }

      public string to_string()
      {
         return (to == null) ? "NULL" : "Example: %.5f".printf(to);
      }
   }

   public class Test
   {
      public static void main(string[] args)
      {
         stdout.printf("Start test\n");

         Example ex = new Example();

         stdout.printf("%s\n", ex.to_string());
         ex.set_to(5.0);
         stdout.printf("%s\n", ex.to_string());

         stdout.printf("End test\n");
      }
   }
}

【问题讨论】:

    标签: generics interface compiler-errors vala


    【解决方案1】:

    不要使用IExample&lt;double&gt;,而是使用IExample&lt;double?&gt;double 装箱,以便它可以作为指针传递。通常,这对于 Vala 中的任何 struct 类型都是必需的。类和紧凑类不需要这种处理,因为它们已经是指针。此外,struct 小于 32 位(即使在 64 位平台上)的类型,例如 uint8char 可以直接使用而无需装箱。如有疑问,请框。

    【讨论】:

    • 谢谢。我接受了您的回答并发布了带有上面代码的版本。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多