alias - 如何将 std.typecons.Typedef 与函数一起使用?

标签 alias d typedef initializer

我有:

typedef void function(int) handler = &noOp;

由于 typedef 已被弃用,我被告知使用别名(不允许设置默认初始值设定项)或 std.typecons.Typedef(允许设置)。但是,以下方法不起作用:

import std.typecons;
alias handler = Typedef!(void function(int), &noOp);

如何在没有 typedef 的情况下设置函数类型的初始值设定项?

最佳答案

这是了解基础知识的一个很好的例子 - 我认为了解 struct 的来龙去脉比 Typedef 更有帮助,因为你可以做很多事情更多与它。执行此操作的方法如下:

void noOp(int) {} 
struct handler { 
    void function(int) fn = &noOp;  // here's the initializer
    alias fn this;  // this allows implicit conversion
} 
void main() { 
    handler h; 
    assert(h == &noOp); // it was initialized automatically!
    static void other(int) {} 
    h = &other; // and you can still reassign it
} 

alias this 可能存在争议 - 它允许与基本类型之间的隐式转换,如 alias,但这与 typedef 不同>。您还可以通过执行单独的构造函数、opAssign 重载等来自定义它,具体取决于您需要的具体行为。问我,我可以澄清,但你也会想玩一下它,看看你是否喜欢它现在的工作方式。

关于alias - 如何将 std.typecons.Typedef 与函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31440023/

相关文章:

search - 在ElasticSearch中搜索使用别名

c++ - 使用模板的动态特征声明类型

compiler-construction - CTFE如何运作?

linux - 如何将 bash 别名添加到 .bashrc 以接受参数?

javascript - 可以使用 "alias"或 "macro"来调用 HTML 中的 JavaScript 函数吗?

d - 负实数的幂

exception - continue 不在循环内

enums - C 中枚举声明之间的区别?

c - 在 typedef struct 中指定结构名称

c - typedef 固定长度数组 -> 自动扩展大小?