我有以下小例子(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");
}
}
}