d的用定属

import std.traits;
import std.getopt;

// 指定参数结构
struct Options
{
    @Option("threads", "t")
    @Help("要用线程数")
    size_t threads;

    @Option("file")
    @Help("输入文件")
    string[] files;
}

void main(string[] args) {
    Options prop;

    // 插件要求完整语句
    string GenerateGetopt(alias Options)() pure {
        import std.meta;
        import std.typecons;
        import std.format;
        auto ans = `auto helpInfo = getopt(args, `;
        static foreach(opt; FieldNameTuple!Options) {
            // getUDAs 取指定类型的`用定属`
            ans ~= format("getUDAs!(prop.%s, Option)[0].cononical(),"
              ~" getUDAs!(prop.%s, Help)[0].msg, &prop.%s,", opt, opt, opt);
        }

        return ans ~ ");";
    }

    // 传递待生成`用定属`结构
    mixin(GenerateGetopt!Options);

    if (helpInfo.helpWanted)
    {
        defaultGetoptPrinter("选项: ",helpInfo.options);
        //控制台输出
        //选项:
        //-t --threads 要用线程数
        //      --file 输入文件
        //-h    --help 本帮助信息
    }
}

// 用定属类型

struct Help {
    string msg;
}

struct Option {
    string[] names;

    this(string[] names...) {
        this.names = names;
    }

    string cononical() {
        import std.algorithm;
        import std.conv;
        return names.joiner("|").to!string;
    }
}

posted @ 2021-09-17 14:26  zjh6  阅读(15)  评论(0)    收藏  举报  来源