d插件模板问题
mixin template helper() {
mixin("writeln(12);");
}//
struct Foo {
void opDispatch(string name)() {
import std.stdio;
mixin helper!();
//mixin("writeln(12);");//这有问题
}
}
void main() {
Foo.init.opDispatch!"bar"();
}
mixin template
不能这样用.它仅接受声明
语句,在此.
插件模板
仅用来声明新的变量,类型和函数
,它不能简单地你那样放call
语句.你可:
void helper()
{
writeln(12);
}
插件
模板不能直接带语句
,因此需要改两下
才能使代码
正常工作:
更改插件
模板为如下:
mixin template helper() {
// 在此函数中放语句
void helper() {
mixin("writeln(12);");
}
}
更改实例化
位置为:
struct Foo {
void opDispatch(string name)() {
import std.stdio;
mixin helper!();
helper(); // 在插件模板中,调用函数
}
}
为什么不直接使用opDispatch()
的插件
模板呢?
mixin template helper() {
void opDispatch(string name)() {
import std.stdio;
writeln(12);
}
}
struct Foo {
mixin helper;
// ...
}
void main() {
Foo.init.opDispatch!"bar"();
}
有种技术可解决该插件模板
限制,我现在找不到.
变通方案
不需要更改用户.如下:
mixin template myStatement() {
auto doIt() {
import std.stdio : writeln;
writeln("hi");
return 0;
}
auto ignoreThis = doIt();
}
void main() {
mixin myStatement!();
mixin myStatement!();
}
opDispatch
根据传入参数
生成代码
,根据类型
插入变量名和函数
.我想删除静每一
中的双括号
(因为在其中声明了些别名
,需要这样做,但因为创建
了一个外部
不能引用
这些新变量的域,要用双括号).
我在此看到了亚当
的帖子.展示了"助手"模板
.从此,我去掉了双大括号
,去掉了别名
,虽然不那么简洁
,但很管用
.
这并不是插件
模板的目的,它们只是复制
声明到域中的(因此
只支持声明),相反,你需要的是
template helper() {
const char[] helper = `writeln(12);`;
}
struct Foo {
void opDispatch(string name)() {
import std.stdio;
mixin(helper!());
}
}
void main() {
Foo.init.opDispatch!"bar"();
}
在函数中,你可根据整个环境
,用普通
的foreach
代替静每一
来简化
事情.
在禁止了普通foreach
和双大括号
的函数外
中,助手
对象很有用.
还可以这样:
template MyContainer(string varS = "")
{
struct Var
{
import std.variant;
private
Variant[string] values;
alias values this;
@property {
Variant opDispatch(string name)() const
{
return values[name];
}
void opDispatch(string name, T)(T val)
{
values[name] = val;
}
}
}
static if(varS.length > 0)
{
import std.format;
mixin(varS.format!"Var %s;");
} else
Var data;//这里.
}
void main()
{
//otherTest("test ok");/*
mixin MyContainer!"date";
enum Tarih { AY = 1, YIL = 2023 }
date.month = cast(ubyte)Tarih.AY;
date.month.write("/");
assert(date["month"] != Tarih.AY); //原因
assert(date["month"].type == typeid(ubyte));
date.year = cast(short)Tarih.YIL;
date.year.writeln("土耳其格式");
assert(date["year"] != Tarih.YIL); //
assert(date["year"].type == typeid(short));
writefln("Date: %s/%s", date.year, date.month);//*/
} /* Prints:
1/2023 in Turkish format
Date: 2023/1
//*/
import std.stdio;
void otherTest(string str)
{
mixin MyContainer;
data.test = str;
data.test.writeln;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现