我正在尝试创建一个能够打印出它的值的泛型类。
class Point<T>
{
public T x {get; set; default = 0;}
public T y {get; set; default = 0;}
public void print()
{
stdout.puts(@"x: $x, y: $y\n");
}
}
int main(string[] args)
{
var point = new Point<int>();
point.x = 12;
point.y = 33;
point.print();
return 0;
}
编译器给了我这些错误:
main.vala:8.21-8.22: error: The name `to_string' does not exist in the context of `T'
stdout.puts(@"x: $x, y: $y\n");
^^
main.vala:8.28-8.29: error: The name `to_string' does not exist in the context of `T'
stdout.puts(@"x: $x, y: $y\n");
^^
有没有办法解决这个问题?
答案 0 :(得分:4)
不直接。您需要传递一个代表来打印您的项目:
delegate string Stringify<T>(T item);
class Point<T>
{
public T x {get; set; default = 0;}
public T y {get; set; default = 0;}
public void print(Stringify<T> stringifier)
{
stdout.puts(@"x: $(stringifier(x)), y: $(stringifier(y))\n");
}
}
int main(string[] args)
{
var point = new Point<int>();
point.x = 12;
point.y = 33;
point.print(int.to_string);
return 0;
}
或者,您可以像Gee那样构建一组特殊情况: https://github.com/GNOME/libgee/blob/master/gee/functions.vala#L49