从 D 中的 class 访问泛型参数

Access the generics arguments from a class in D

我有一个 class,它接受一个通用参数

class A(T) {}

我希望能够访问它的值。

我该怎么做。

虽然我可以在 returns T 的 A 中编写一个函数,这是个好主意吗,或者是否有另一种方法来访问 class 之外的类型参数 T一个?

TemplateArgsOf 在 std.traits 应该做你想做的事。

您可以在 A 中为 T 定义一个别名,它将 return T 的实际 "value"(类型)。例如:

class A(T)
{
    alias type = T;
}

auto a = new A!int();
assert(is(a.type == int));

我在运行时创建了一个新的 A!int 只是为了说明。 typeA!T 的一种静态成员,您可以在编译时访问它。

assert(is(A!double.type == double));

您还可以轻松提取 A 使用模板实例化的类型:

alias InstantiationType(_: u!T, alias u, T) = T;
assert(is(InstantiationType!(A!int) == int));

幸运的是,如前所述,此功能以 TemplateArgsOf.

的形式预先打包在 Phobos 的 std.traits 中