微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法进行早期绑定的 Nim 模板?

如何解决无法进行早期绑定的 Nim 模板?

build_type 库中定义了 lib.nim 模板。

template build_type*[T](_: type[T]): T = T.build()

对象 B 使用该模板来构建对象 A

而且它不起作用 - 因为虽然 Ab.nim 中可见,但它在 main.nim 中不可见,其中使用了 B

如果 A 导入到 main.nim 中它可以工作(请参阅注释掉的导入),但感觉不对,因为它破坏了 B 内部细节的封装(因为代码使用 {{1 }} 也应该导入 B,即使它不使用 A)。

我想知道是否还有其他方法可以让它发挥作用?

playground

A

编译错误

# main.nim ------------------------------------------
import bobject #,aobject

echo B.build()

# bobject.nim ---------------------------------------
import lib,aobject

type B* = tuple[a: A]

proc build*(_: type[B]): B = (a: build_type(A))

# aobject.nim ---------------------------------------
type A* = tuple[v: int]

proc build*(_: type[A]): A = (0,)

# lib.nim -------------------------------------------
template build_type*[T](_: type[T]): T = T.build()

解决方法

我会将 #include <stdio.h> // printf,scanf,putchar #include <float.h> // FLT_EPSILON #include <math.h> // fabs int isequal(double,double); int main(void) { double min,max,step,nnum; printf("Maximum: "),scanf("%lf",&max); // Get maximum printf("Minimum: "),&min); // Get minimum if (min > max) { // If invalid maximum,handle error puts("Maximum cannot be over minimum"); return 1; // Returning 1 indicates program failure } printf("Step: "),&step); // Get step nnum = (max - min)/step; if (!isequal(nnum,(int) nnum) || step <= 0) { // If invalid step,handle error puts("Invalid step"); return 1; } putchar('\n'); // Separate input from output for (int i = 0; i <= nnum; i++) { printf("%d. %lf\n",i + 1,min); min += step; // We already know it will go into maximum evenly } return 0; // Returning 0 indicates program success } int isequal(double x,double y) { // fabs() = Float absolute value return fabs(x - y) < FLT_EPSILON; // FLT_EPSILON = Smallest comparable float value } 更改为:

bobject.nim

并将 proc initB*(): B = (a: build_type(A)) 修正为:

main.nim

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。