Custom 'image attribute in Ada?

断了今生、忘了曾经 提交于 2019-12-23 10:50:08

问题


So I have a thing.

type Thing is new record
  ...elements...
end record;

I have a function which stringifies it.

function ToString(t: Thing) returns string;

I would like to be able to tell Ada to use this function for Thing'image, so that users of my library don't have to think about whether they're using a builtin type or a Thing.

However, the obvious syntax:

for Thing'image use ToString;

...doesn't work.

Is there a way to do this?


回答1:


I don’t know why the language doesn’t support this, and I don’t know whether anyone has ever raised a formal proposal that it should (an Ada Issue or AI). The somewhat-related AI12-0020 (the 20th AI for Ada 2012) includes the remark "I don't think we rejected it for technical reasons as much as importance”.

You can see why the Ada Rapporteur Group might think this was relatively unimportant: you can always declare an Image function; the difference between

Pkg.Image (V);

and

Pkg.Typ’Image (V);

isn’t very large.




回答2:


One common method is to create a unary + function...

    function "+"(item : myType) return String;

which is syntactically very light. Obvious disclaimer: may lead to some ambiguity when applied to numeric types (e.g. Put (+4);)

However there is still the distinction between prebuilt types and user defined types. 'img wouldn't be able to be used by your client's code though, unless you specified an interface that enforced this function to be present (what if the client called on 'img for a private type that didn't have a 'img function defined?).

If you end up having to have an interface, it really doesn't matter what the function is called.



来源:https://stackoverflow.com/questions/23982388/custom-image-attribute-in-ada

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!