3

我有以下小例子(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 代码时,它显示示例的 set_to 函数采用双精度,而 IExample 的 set_to 函数采用 gconstpointer。

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

感谢您的帮助。

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

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

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");
      }
   }
}
4

1 回答 1

1

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

于 2012-12-31T14:38:18.373 回答