简体   繁体   English

如何获得模块的所有成员/功能?

[英]How to get all members / functions of a module?

module testmodule;

struct testmodule {}

pragma(msg, __traits(allMembers, testmodule));
pragma(msg, __traits(allMembers, .testmodule));

Prints: 打印:

tuple()
tuple()

How do I do it when a declaration in the module has the name of the module? 当模块中的声明具有模块名称时,该怎么办?

For the specific case where you know testmodule refers to a struct that is a child of the module testmodule , you can use: 对于您知道具体情况testmodule指结构是模块的子testmodule ,你可以使用:

pragma(msg, __traits(allMembers, __traits(parent, testmodule));

If you need to determine whether or not a symbol is actually a module, here's something I threw together quickly that seems to work: 如果您需要确定一个符号是否实际上是一个模块,这里的东西我扔在一起,很快, 似乎工作:

template isModule(alias sym) {
  enum isModule = !__traits(compiles, sym.sizeof);
}

static assert(!isModule!testmodule);
static assert(isModule!(__traits(parent, testmodule)));

I'm basically guessing that anything other than a module will have a sizeof property, but I may be forgetting some other kind of non-module symbol which does not have sizeof . 我基本上是在猜测模块以外的任何东西都将具有sizeof属性,但是我可能会忘记其他没有sizeof其他非模块符号。

No built-in mechanism for this disambugation is provided because usually compiler can figure it on its own and such necessity was simply not foreseen. 没有提供用于这种错误解释的内置机制,因为通常编译器可以自行解决它,而根本没有预见到这种必要性。

Here is a simple library utility that generalizes approach proposed by @rcorre (nice idea!): 这是一个简单的库实用程序,可以概括@rcorre提出的方法(很好的主意!):

module getmod;

struct getmod {};

template isModule(alias sym)        
{
    static if (is(typeof(sym) == function))
        enum isModule = false;
    else
    {
        import std.array : startsWith;
        enum isModule = sym.stringof.startsWith("module ");
    }
}

template Module(alias sym)
    if (isModule!sym)
{
    alias Module = sym;
}

template Module(alias sym)
    if (!isModule!sym)
{
    import std.typetuple : TT = TypeTuple;
    alias Module = TT!(__traits(parent, sym))[0];
}

pragma(msg, __traits(allMembers, Module!getmod));
// tuple("object", "getmod", "isModule", "Module", "main")

This is not as good as built-in symbol disamgutation but should be practical enough. 这不如内置符号删除功能好,但应该足够实用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM