Vala接口泛型编译错误

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代码时,它显示Example的set_to函数采用double,而IExample的set_to函数采用gconstpointer。
那么为什么主函数使用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");
      }
   }
}
1个回答

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

谢谢。我采纳了你的答案并在上面发布了带有代码的版本。非常感谢。 - Jason Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接