指向perl6中的类的构造函数的指针

问题描述 投票:6回答:2

我正在尝试用Perl 6编写一些类来测试Perl 6类和方法。

这是代码:

class human1 {
    method fn1() {
        print "#from human1.fn1\n";
    }
}

class human2 {
    method fn1() {
          print "#from human2.fn1\n";
    }
}

my $a = human1.new();
my $b = human2.new();

$a.fn1();
$b.fn1();

print "now trying more complex stuff\n";

my $hum1_const = &human1.new;
my $hum2_const = &human2.new;

my $c = $hum2_const();
$c.fn1();

基本上我希望能够使用human1构造函数或human2构造函数来动态构建$c对象。但是我收到以下错误:

Error while compiling /usr/bhaskars/code/perl/./a.pl6
Illegally post-declared types:
    human1 used at line 23
    human2 used at line 24

如何使用函数指针创建$c以选择我使用的构造函数?

class perl6
2个回答
4
投票

我认为这是LTA错误的一个例子。我理解你想要实现的是一个lambda,它将为你创建一个新的human1human2对象。你这样做的方式是不正确的,它引起的错误令人困惑。

my $hum1_const = -> { human1.new };
my $hum2_const = -> { human2.new };

这是一个正确的方法。虽然,我认为这有点混淆。由于human1human2已经是常量,你可以将它们分配给变量,然后只需调用new

my $the_human = $condition ?? human1 !! human2;
my $c = $the_human.new;
$c.fn1;

那有意义吗?


4
投票

要获得.new的“参考”,您必须使用元对象协议。 无论是.^lookup,还是.^find_method

my $hum1-create = human1.^find_method('new');

这仍然不是你想要的,因为方法需要一个类对象或一个实例作为他们的第一个参数。

my $c = $hum1-create( human1 );

所以你可能想把这个类作为该方法的第一个参数。

my $hum1-create = human1.^find_method('new').assuming(human1);

my $c = $hum1-create();

请注意,在这种情况下.assuming基本上做同样的事情

-> |capture { human1.^find_method('new').( human1, |capture ) }

所以你可以写:

my $hum1-create = -> |capture { human1.new( |capture ) }

或者,如果你永远不会给它一个论点

my $hum1-create = -> { human1.new }

您也可以将它存储在& sigiled变量中,这样您就可以像使用普通子程序一样使用它。

my &hum1-create = human1.^find_method('new').assuming(human1);

my $c = hum1-create;
© www.soinside.com 2019 - 2024. All rights reserved.