如何让重载函数指向其他函数?Delphi函数重定向方案咨询
Delphi中实现重载函数映射到已有函数的可行方法
你定义了以下函数:
function ALmyfunctA(const Filename: AnsiString): Boolean; function ALmyfunctW(const Filename: String): Boolean; function ALmyfunct(const Filename: AnsiString): Boolean; overload; function ALmyfunct(const Filename: String): Boolean; overload;
想要让两个重载的ALmyfunct分别直接映射到ALmyfunctA和ALmyfunctW,但用函数指针变量的方式不支持重载特性,这里提供可行的实现方式:
极简内联转发(推荐)
直接在重载函数的实现里调用对应的目标函数,代码量极小,完全符合重载需求:
function ALmyfunct(const Filename: AnsiString): Boolean; overload; begin Result := ALmyfunctA(Filename); end; function ALmyfunct(const Filename: String): Boolean; overload; begin Result := ALmyfunctW(Filename); end;
这种方式本质是让重载函数做“透传”,编译时会被优化成直接调用目标函数,几乎没有性能损耗,同时完美支持overload特性。
为什么函数指针变量不行?
Delphi的函数指针变量只能绑定单一签名的函数,不支持重载特性,所以无法通过var ALmyfunct: function(...)的方式实现重载版本的映射。
内容的提问来源于stack exchange,提问作者zeus
相关产品推荐
相关产品推荐

