in reply to Overloading different instances differently.

Seems like overkill. Overloading is just a special syntax for a behind the scenes method call. Just make your method call implementing the overload examine the instance its called on and vary what it does accordingly instead.

Simplest implementation that comes to mind is have the name of the overload method you really want called on the method stored in the instance. If that's too constraining you could also store a coderef for the behavior instead and have the overload method just call that.

The cake is a lie.
The cake is a lie.
The cake is a lie.

  • Comment on Re: Overloading different instances differently.

Replies are listed 'Best First'.
Re^2: Overloading different instances differently.
by tilly (Archbishop) on Feb 22, 2008 at 22:18 UTC
    Problem. Suppose for one object you overload '""'. With his solution you've also overloaded 'bool' and '0+' in the way the user of the code probably expects. With your solution all of those implicit overloads have to be spelled out. Or else you've got to build all of the dispatch logic that is already built into overload.

      Erm, no. I'm just talking about making the method called by the normal overload call examine the instance in question to decide what to do. I don't see how that would change anything about the automagically generated boolification or numification logic.

      #!/usr/bin/perl use strict; use warnings; package Ovl; use overload '""' => \&mystring; sub new { my $ret = bless {}, shift(); $ret->{_name} = shift; $ret->{_str_code} = \&_str_default; return $ret; } sub _str_default { my $self = shift; "!" . $self->{_name} . "!" } sub mystring { my $self = shift; my $str_code = $self->{_str_code} || \&_str_default; $self->$str_code( @_ ); } package main; my $o = Ovl->new( "default" ); print "$o\n"; my $o_undef = Ovl->new( undef ); $o_undef->{_str_code} = sub { "I R UNDEFINED" }; print "$o_undef\n" if $o_undef; my $o_numeric = Ovl->new( 15 ); $o_numeric->{_str_code} = sub { sprintf( "%0.5f", shift->{_name} ) }; print "$o_numeric\n" if int( $o_numeric ) == 15; exit 0; __END__

      Update: AAAAAHHH. Just reread the OP's code and I see what you're getting at. In order to implement arbitrary overload operations on instances (i.e. what operations are overloaded on the instance, not just what each operation does on each instance) you would need to have defined handlers for all possible operations for the class itself and then yes you would need duplicate dispatching logic. I was thinking of the case where each instance shared the same set of overloaded operations, whereas his allows instance level selection of what's overloaded. I just glanced over his code and missed that he was trying to get different sets of overload behavior per instance. Bah, it's quitting time on Friday.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.