d匹配模板类型结构实例

原文

import core.stdc.stdio;

Test!(T, "mode1") make_test(T)(T data) {
  Test!(T, "mode1") t = { data };

  return t;
}

struct Test(T, string mode = "ref") { T data; }

extern (C) void main() {
  auto obj = make_test(20);
  static if (is(typeof(obj) == Test)) { printf("YES!!!!!!!\n"); }
}

我可以:

static if (is(typeof(obj) == Test!(int, "mode1"))) { printf("YES!!!!!!!\n"); }

这样:

static if (is(typeof(obj) == Test!T, T)) { printf("YES!!!!!!!\n"); }
//超过1个模板参数,要求括号

多参,这样:

static if (is(typeof(obj) == Test!Args, Args...))

还可这样:

import std.traits;
static if (isInstanceOf!(Test, typeof(obj))) { printf("YES!!!!!!!\n"); }
//这样.

现在,可简化日志为:

struct LOG(T...) {
  T[0] id;
  T[1] data;
}

void main()
{
   auto obj = //make_test(20);/*
              make_test('T');//*/

  alias typ = //typeof(obj);/*
        LOG!(int, char);//*/

  "Type: ".write;

  if(isInstanceOf!(LOG, typ)/*
    is(typ : Template!Args,
    alias Template, Args...)//*/
  ) "LOG".writeln;
}
posted @ 2022-07-13 09:07  zjh6  阅读(13)  评论(0)    收藏  举报  来源