在 Moose 属性访问器上进行字符串重载的最佳方法是什么?

发布于 2024-12-01 16:19:25 字数 746 浏览 1 评论 0原文

我有一个类,我想在其 id 属性上应用字符串重载。但是,Moose 不允许属性访问器上的字符串重载。例如:

package Foo;
use Moose;
use overload '""' => \&id, fallback => 1;
has 'id' => (
    is => 'ro',
    isa => 'Int',
    default => 5,
);

package main;
my $foo = Foo->new;
print "$foo\n";

上面的代码会报错:

You are overwriting a locally defined method (id) with an accessor at C:/perl/site/lib/Moose/Meta/Attribute.pm line 927

我尝试了几个选项来解决这个问题:

  1. Marking id is => bare,并将其替换为我自己的访问器:sub id {$_[0]->{id}}。但这只是一个 hack。

  2. 让字符串重载器使用另一种仅委托回 id 的方法:sub to_string {$_[0]->id}

我只是想知道是否有人有更好的方法来做到这一点?

I have a class where I want to apply string overloading on its id attribute. However, Moose doesn't allow string overloading on attribute accessors. For example:

package Foo;
use Moose;
use overload '""' => \&id, fallback => 1;
has 'id' => (
    is => 'ro',
    isa => 'Int',
    default => 5,
);

package main;
my $foo = Foo->new;
print "$foo\n";

The above will give an error:

You are overwriting a locally defined method (id) with an accessor at C:/perl/site/lib/Moose/Meta/Attribute.pm line 927

I have tried a couple of options to get around this:

  1. Marking id is => bare, and replacing it with my own accessor: sub id {$_[0]->{id}}. But this is just a hack.

  2. Having the string overloader use another method which just delegates back to id: sub to_string {$_[0]->id}.

I'm just wondering if anyone has a better way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

楠木可依 2024-12-08 16:19:25
use overload '""' => sub {shift->id}, fallback => 1;

对我来说效果很好。

use overload '""' => sub {shift->id}, fallback => 1;

Works fine for me.

爱本泡沫多脆弱 2024-12-08 16:19:25

我相信您收到错误是因为 \&id 为稍后定义的 sub 创建了一个占位符,因为 Perl 需要知道 sub 在定义时将具有的地址以创建引用到它。 Moose 有自己的检查来尝试避免覆盖您定义的方法并向您报告。

因为我认为你真正想做的是当对象用作刺时调用 id 方法,如下所示:

use overload '""' => 'id', fallback => 1;

来自 重载文档

指定为字符串的值将被解释为方法名称。

I believe you are getting an error because \&id creates a placeholder for a sub to be defined later, because Perl will need to know the address that sub will have when it is defined to create a reference to it. Moose has it's own checks to try to avoid overwriting methods you define and reports this to you.

Since I think what you really want to do is call the id method when the object is used as a sting like so:

use overload '""' => 'id', fallback => 1;

From the overload documentation

Values specified as strings are interpreted as method names.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文