在 Moose 属性访问器上进行字符串重载的最佳方法是什么?
我有一个类,我想在其 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
我尝试了几个选项来解决这个问题:
Marking
id
is => bare
,并将其替换为我自己的访问器:sub id {$_[0]->{id}}
。但这只是一个 hack。让字符串重载器使用另一种仅委托回 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:
Marking
id
is => bare
, and replacing it with my own accessor:sub id {$_[0]->{id}}
. But this is just a hack.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说效果很好。
Works fine for me.
我相信您收到错误是因为
\&id
为稍后定义的 sub 创建了一个占位符,因为 Perl 需要知道 sub 在定义时将具有的地址以创建引用到它。 Moose 有自己的检查来尝试避免覆盖您定义的方法并向您报告。因为我认为你真正想做的是当对象用作刺时调用
id
方法,如下所示:来自
重载
文档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:From the
overload
documentation