首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

泛型和元编程的模型:Java, Go, Rust, Swift, D等

在程序设计的时候,我们通常希望使用同样的数据结构或算法,就可以处理许多不同类型的元素,比如通用的List或只需要实现compare函数的排序算法。对于这个问题,不同的编程语言已经提出了各种各样的解决方案:从只是提供对特定目标有用的通用函数(如C,Go),到功能强大的图灵完备的通用系统(如Rust,C++)。在本文中,我将带你领略不同语言中的泛型系统以及它们是如何实现的。我将从C这样的不具备泛型系统的语言如何解决这个问题开始,然后分别展示其他语言如何在不同的方向上逐渐添加扩展,从而发展出各具特色的泛型系统。 泛型是元编程领域内通用问题的简单案例:编写可以生成其他程序的程序。我将描述三种不同的完全通用的元编程方法,看看它们是如何在泛型系统空的不同方向进行扩展:像Python这样的动态语言,像Template Haskell这样的过程宏系统,以及像Zig和Terra这样的阶段性编译。

03

iOS Category实现原理

// Attach method lists and properties and protocols from categories to a class. // Assumes the categories in cats are all loaded and sorted by load order, // oldest categories first. static void attachCategories(Class cls, category_list *cats, bool flush_caches) { if (!cats) return; if (PrintReplacedMethods) printReplacements(cls, cats); bool isMeta = cls->isMetaClass(); // fixme rearrange to remove these intermediate allocations method_list_t **mlists = (method_list_t **) malloc(cats->count * sizeof(*mlists)); property_list_t **proplists = (property_list_t **) malloc(cats->count * sizeof(*proplists)); protocol_list_t **protolists = (protocol_list_t **) malloc(cats->count * sizeof(*protolists)); // Count backwards through cats to get newest categories first int mcount = 0; int propcount = 0; int protocount = 0; int i = cats->count; bool fromBundle = NO; while (i--) { auto& entry = cats->list[i]; method_list_t *mlist = entry.cat->methodsForMeta(isMeta); if (mlist) { mlists[mcount++] = mlist; fromBundle |= entry.hi->isBundle(); } property_list_t *proplist = entry.cat->propertiesForMeta(isMeta, entry.hi); if (proplist) { proplists[propcount++] = proplist; } protocol_list_t *protolist = entry.cat->protocols; if (protolist) { protolists[protocount++] = protolist; } } auto rw = cls->data(); prepareMethodLists(cls, mlists, mcount, NO, fromBundle); rw->methods.attachLists(mlists, mcount); free(mlists); if (flush_caches && mcount > 0) flushCaches(cls); rw->properties.attachLists(proplists, propcount); free(proplists); rw->protocols.attachLists(protolists, protocount); free(protolists); }

02
领券