Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++-like usage of Moose with Perl for OOP

Tags:

c++

oop

perl

moose

I've been playing around with Moose, getting a feel for it. I'd like an example of pure virtual functions like in C++ but in Moose parlance (specifically in a C++-looking way). I know that even with Moose imposing a stricter model than normal Perl, there's still more than one way to do what I'm asking (via method modifiers or SUPER:: calls). That is why I'm asking specifically for an implementation resembling C++ as much as possible. As for the "why?" of this restriction? Mostly curiosity, but also planning to port some C++ code to Perl with Moose in a way that C++-centric people could mostly identify with.

like image 555
Kyle Walsh Avatar asked Aug 27 '09 15:08

Kyle Walsh


3 Answers

I can think of this way using roles instead of subclassing:

{
    package AbstractRole;
    use Moose::Role;
    requires 'stuff';  
}

{
    package Real;
    use Moose;
    with 'AbstractRole';
}

This will give a compilation error because Real doesn't have stuff defined.

Adding stuff method to Real will now make it work:

{
    package Real;
    use Moose;
    with 'AbstractRole';

    sub stuff { print "Using child function!\n" }
}
like image 139
draegtun Avatar answered Nov 04 '22 08:11

draegtun


You might also want to take a look at Jesse Luehrs' MooseX::ABC. It seems very similar to some of the implementations here. From the synopsis:

package Shape;
use Moose;
use MooseX::ABC;

requires 'draw';

package Circle;
use Moose;
extends 'Shape';

sub draw {
    # stuff
}

my $shape = Shape->new; # dies
my $circle = Circle->new; # succeeds

package Square;
use Moose;
extends 'Shape'; # dies, since draw is unimplemented

I know that Jesse is a C++ programmer during the day.

like image 29
perigrin Avatar answered Nov 04 '22 09:11

perigrin


Here is was my attempt (without Roles, for information on Roles see the other answers):

package Abstract;
use Moose;

sub stuff;

package Real;
use Moose;
extends 'Abstract';

override 'stuff' => sub { print "Using child function!\n"; }
like image 2
Kyle Walsh Avatar answered Nov 04 '22 10:11

Kyle Walsh