我希望能够在模板中比较两个typedesc,以查看它们是否引用相同的类型(或至少具有相同的类型名称),但不确定如何使用。 ==运算符不允许这样做。

type
  Foo = object
  Bar = object

template test(a, b: expr): bool =
  a == b

echo test(Foo, Foo)
echo test(Foo, Bar)

它给了我这个:
 Error: type mismatch: got (typedesc[Foo], typedesc[Foo])

如何才能做到这一点?

最佳答案

is运算符可帮助:http://nim-lang.org/docs/manual.html#generics-is-operator

type
  Foo = object
  Bar = object

template test(a, b: expr): bool =
  #a is b # also true if a is subtype of b
  a is b and b is a # only true if actually equal types

echo test(Foo, Foo)
echo test(Foo, Bar)

10-04 11:13
查看更多