问题
I have the following small example(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");
}
}
}
This throws the error:
/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)
Now from what little documentation I have been able to find on generics interfaces in Vala, http://www.vala-project.org/doc/vala-draft/generics.html#genericsexamples, this should work. When I check the resulting C code, it shows the Example's set_to function as taking a double and the IExample's set_to function as taking a gconstpointer.
So why is the main function then using the gconstpointer version instead of the double version? Can some one explain to me why it does not work and a way to get around it?
Thank you for your help.
P.S. Yes I know the documentation found is a draft document.
ANSWER CODE: According to the selected answer below this is what I changed the code to.
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:
Rather than using IExample<double>
, use IExample<double?>
to box the double
so that it can be passed as a pointer. This necessary, generally, for any struct
type in Vala. Classes and compact classes do not need this treatment, as they are already pointers. Also, struct
types that are smaller than 32-bits (even on 64-bit platforms) such as uint8
or char
can be used directly without boxing. When in doubt, box.
来源:https://stackoverflow.com/questions/14096999/vala-interface-generics-compiler-error